# Collection fields

> Read when a model holds rows by key. Declare a CollectionField, decode it from a plain array, write a refetch that keeps rows equal under the schema, and reconcile a schema-checked box of an array.

The Effect pages are for applications that already use Effect: see
[Schema-checked boxes](./boxes.md). A `CollectionField` is the core's
[collection](../state/collections.md) 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](./classes.md):

```ts
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));
    });
  }
}
```

```ts
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);
    });
  }
}
```

```ts
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)); // 1
```

A 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.

```ts
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](./equality.md) 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.

```ts
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.

```ts
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.

```ts
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 `CollectionField` checks each row against the row schema when it
  lands: on `decode`, `write.upsert`, and `write.replaceAll`. A row the schema
  rejects throws from the update, which rolls back. A `schemaCollection`
  checks on `write.upsert` and `write.replaceAll` the same way.
- An `undefined` row is rejected with `pinna: a collection row cannot be
  undefined`, even when the row schema accepts it: `row(key)` and
  `read.row` use `undefined` for a missing key. `decode` throws a
  `Schema.SchemaError` with that message and an Effect decode fails with
  it, before `keyOf` runs; `make` throws its schema error;
  `write.upsert` and `write.replaceAll` throw 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 `decode` and throws from
  `write.replaceAll`, both with `pinna: the collection key <key> appears twice`.
  `reconcile` and `reconcileSchema` throw
  `pinna: reconcile: the key <key> appears twice`.
- A row with a `$` field is a new instance after every `decode`, with new
  boxes. `replaceAll`, `upsert`, and `reconcileSchema` merge 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](./equality.md).

## 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](../state/updates.md), with `equals` optional and a `SchemaModel` item merged into the held one. |

## See also

- [Collections](../state/collections.md): reading and writing a collection, and rendering one row per key.
- [Classes](./classes.md): the model a collection field lives on.
- [Updates](../state/updates.md): the update every write runs in.
- [Hooks](../react/hooks.md): a row component that rerenders alone.
- [Equality and hashing](./equality.md): a row class's own `Equal`, and what each schema counts as equal.
- [Live data](../guides/live-data.md): a refetch and a feed written into a collection field.
