Collection fields
The Effect pages are for applications that already use Effect: see
Schema-checked boxes. A CollectionField is the core’s
collection as a field of a SchemaModel: it is
read with row(key), read.row, keys, and rows, and written with write.upsert,
write.remove, and write.replaceAll, as that page shows.
Example
A CollectionField holds rows by key, each row checked against the
row schema. On the wire it is a plain array. The rows here are the Todo of
Classes:
import { BoxField, computed, createRealm, SchemaModel, update } from "@frondruntime/pinna-effect";
import { Schema } from "effect";
const realm = createRealm();
class Todo extends SchemaModel<Todo>("Todo")({
id: Schema.String,
title: Schema.String,
$done: BoxField(Schema.Boolean), // a box field; the wire key is "done"
}) {
readonly $label = computed(this.realm, (read) =>
read(this.$done) ? `✓ ${this.title}` : this.title,
);
toggle(): void {
update(this.realm, (read, write) => {
write(this.$done, !read(this.$done));
});
}
}import { CollectionField, computed, SchemaModel, update } from "@frondruntime/pinna-effect";
class TodoList extends SchemaModel<TodoList>("TodoList")({
$items: CollectionField(Todo, { keyOf: (todo) => todo.id }),
}) {
readonly $open = computed(
this.realm,
(read) => read(this.$items.rows).filter((todo) => !read(todo.$done)).length,
{ name: "TodoList.open" },
);
add(todo: Todo): void {
update(this.realm, (_read, write) => {
write.upsert(this.$items, todo, { at: "end" });
});
}
remove(id: string): void {
update(this.realm, (_read, write) => {
write.remove(this.$items, id);
});
}
}import { decode, untracked } from "@frondruntime/pinna-effect";
// On the wire, a collection is a plain array.
const items = [
{ id: "1", title: "Write the docs", done: false },
{ id: "2", title: "Read them", done: true },
];
const list = decode(realm, TodoList)({ items });
const open = untracked(realm, (read) => read(list.$open)); // 1A refetch writes every row at once with write.replaceAll. A row equal under
the schema to the one held is kept, and what read it does not rerun. A
SchemaModel row with a $ field is merged: the held row stays, and its
boxes take the refetched values.
import { CollectionField, decode, SchemaModel, update } from "@frondruntime/pinna-effect";
import { Schema } from "effect";
// No `$` field, so it is declared as a plain Schema.Class.
class Quote extends Schema.Class<Quote>("Quote")({
symbol: Schema.String,
price: Schema.Number,
}) {}
class Market extends SchemaModel<Market>("Market")({
$quotes: CollectionField(Quote, { keyOf: (quote) => quote.symbol }),
}) {
receive(quotes: ReadonlyArray<Quote>): void {
update(this.realm, (_read, write) => {
// A quote equal to the one held is kept: what read its row does not rerun.
write.replaceAll(this.$quotes, quotes);
});
}
}
const market = decode(realm, Market)({ quotes: [] });
const receiveQuotes = (json: unknown) => {
market.receive(decode(realm, Schema.Array(Quote))(json));
};reconcile takes equals, here the item schema’s equivalence, so a
schemaBox of a plain array keeps the previous object of every item that did
not change. reconcileSchema takes no schema, and works equals out from
each pair of items when it is left out, as
Equality and hashing lists. A plain Schema.Struct row
compares with Effect’s Equal.equals, which never sees a schema, so a
toEquivalence annotation on a Struct is not used there.
import { computedFunction, decode, reconcile, schemaBox, update } from "@frondruntime/pinna-effect";
import { Schema } from "effect";
const Rate = Schema.Struct({ currency: Schema.String, rate: Schema.Number });
const sameRate = Schema.toEquivalence(Rate);
const $rates = schemaBox(realm, Schema.Array(Rate), []);
const rateOf = computedFunction(realm, (read, currency: string) =>
read($rates).find((rate) => rate.currency === currency),
);
const receiveRates = (json: unknown) => {
const next = decode(realm, Schema.Array(Rate))(json);
update(realm, (read, write) => {
// An unchanged rate keeps its previous object, so rateOf for it
// returns the same value and its readers do not rerun.
write(
$rates,
reconcile(read($rates), next, { keyOf: (rate) => rate.currency, equals: sameRate }),
);
});
};reconcileSchema takes arrays only. One refetched model is a list of one on
each side, under any key, such as a constant: the result is the held
instance, its boxes set to the refetched values, or the refetched instance
when a plain field differs.
import { decode, reconcileSchema } from "@frondruntime/pinna-effect";
// One model, refetched: a list of one on each side. With one item, any key
// does, such as a constant.
const refreshTodo = (held: Todo, json: unknown): Todo => {
const fresh = decode(realm, Todo)(json);
const [next = fresh] = reconcileSchema([held], [fresh], { keyOf: () => "todo" });
return next; // `held`, its $done set to the refetched value, or `fresh`
};schemaCollection is the collection a CollectionField holds, with no model
around it: for rows a service or a feed owns, such as the trades a feed
writes. It starts empty and checks and compares rows as the field does.
import { decode, schemaCollection, update } from "@frondruntime/pinna-effect";
// The collection a CollectionField holds, with no model around it.
const $quotes = schemaCollection(realm, Quote, { keyOf: (quote) => quote.symbol });
const receiveQuote = (json: unknown) => {
// decode checks the wire data; upsert checks the row again as it lands.
const quote = decode(realm, Quote)(json);
update(realm, (_read, write) => {
write.upsert($quotes, quote);
});
};Rules
- A
CollectionFieldchecks each row against the row schema when it lands: ondecode,write.upsert, andwrite.replaceAll. A row the schema rejects throws from the update, which rolls back. AschemaCollectionchecks onwrite.upsertandwrite.replaceAllthe same way. - An
undefinedrow is rejected withpinna: a collection row cannot be undefined, even when the row schema accepts it:row(key)andread.rowuseundefinedfor a missing key.decodethrows aSchema.SchemaErrorwith that message and an Effect decode fails with it, beforekeyOfruns;makethrows its schema error;write.upsertandwrite.replaceAllthrow the message before changing any row. - A row written under a held key is compared with the row schema’s equivalence, so a refetch of equal rows reruns nothing.
- A key names one row. A repeated key fails the
decodeand throws fromwrite.replaceAll, both withpinna: the collection key <key> appears twice.reconcileandreconcileSchemathrowpinna: reconcile: the key <key> appears twice. - A row with a
$field is a new instance after everydecode, with new boxes.replaceAll,upsert, andreconcileSchemamerge it into the row held under its key, so only the readers of a changed box rerun. When they merge is on Equality and hashing.
Answers
| Call | Answers |
|---|---|
CollectionField(schema, { keyOf, name? }) |
A field of rows by key, each checked against schema, a plain array on the wire. name names every instance’s collection, as collection’s does. |
schemaCollection(realm, schema, { keyOf, equals?, name? }) |
An empty collection of rows schema accepts, the one a CollectionField holds. A row is compared with equals, the schema’s equivalence by default, and a SchemaModel row is merged into the held one. |
reconcileSchema(previous, next, { keyOf, equals? }) |
As reconcile on Updates, with equals optional and a SchemaModel item merged into the held one. |
See also
- Collections: reading and writing a collection, and rendering one row per key.
- Classes: the model a collection field lives on.
- Updates: the update every write runs in.
- Hooks: a row component that rerenders alone.
- Equality and hashing: a row class’s own
Equal, and what each schema counts as equal. - Live data: a refetch and a feed written into a collection field.