Reading and writing

Reading a document's value, editing it in transactions, and what optimistic updates mean for your code.

This page covers the everyday API of a client document: how to read its value, how to subscribe to changes, and how to write. It assumes a connected document; see Creating a client.

Reading

getSnapshot() returns the document as plain, immutable data, typed from your schema.

const snapshot = document.getSnapshot();
if (snapshot) {
  console.log(snapshot.title, snapshot.items.length);
}

It returns undefined until the document is ready, and while the document does not exist. The snapshot is the optimistic value: the server's document with this client's unconfirmed edits applied on top. This is what you render.

The same reference is returned until the value changes, and parts of a tree that did not change keep their identity between snapshots, so the snapshot works with memoization and with selectors that compare by reference.

MethodReturns
getSnapshot()The optimistic value, decoded
getServerSnapshot()The value as the server last confirmed it, without pending edits
getPreviewSnapshot()The value as the newest open draft shows it
getValue()The optimistic value in its encoded form
getServerValue()The server's value in its encoded form
getRevision()The revision of the server's value, as a bigint
getServerVersion()The same revision as a number (exact up to 2^53)
getCommitToken()The commit token of the latest change received, or null

Subscribing

const unsubscribe = document.subscribe({
  onStateChange: (snapshot) => render(snapshot),
});

onStateChange runs whenever the value changes, whether the change is a local edit, another user's edit, or a rejected edit being taken back. Call the returned function to stop listening.

Writing

All writes go through a proxy: a typed object that mirrors your schema and turns method calls into commands.

document.transaction((root) => {
  root.title.set("Roadmap");
  root.settings.update({ theme: "dark" });
  root.items.push({ text: "Plan the launch" });
});

transaction runs the function, collects everything it writes into one transaction, applies it to the local value at once, and queues it for the server. The function's return value is returned. Reads inside the function see the writes made so far in it.

A transaction is atomic: other clients see all of its effects or none. Group the writes of one user action into one transaction.

document.root is the same proxy outside a transaction. Each write through it is a transaction of its own:

document.root.title.set("Roadmap");

What a proxy offers

Every proxy has get() to read and set(value) to replace. The rest depends on the primitive:

PrimitiveBesides get and set
String, Number, Boolean, Literal, Eitherupdate(value), the same as set
StructOne property per field (its proxy), and update(fields) to write several fields at once
Unionas(variant) and match(handlers) for the active variant's proxy
Array, TreeSee Lists and trees

A struct's update merges: fields you leave out stay as they are, nested structs merge field by field, and passing undefined for an optional or defaulted field deletes it.

document.transaction((root) => {
  root.update({ title: "Roadmap", subtitle: undefined });
  root.block.as("text").value.set("Hello");
});

as(variant) throws when that variant is not the active one. To switch a union to another variant, set it with a value of that variant.

When a write throws

A write that cannot apply throws, and nothing is queued:

  • ReadOnlyError when the session is read-only (see Connection states and errors).
  • An error from @voidhash/mimic-core (PrimitiveError, SchemaError, CoreError) when the input does not match the schema, or the result would violate it.
  • InvalidStateError when the document is not ready yet, or does not exist.

Because the whole transaction is checked before it is queued, a transaction that throws leaves the document unchanged.

Optimistic updates

A write changes the local value immediately; the server confirms it later. Usually you do not need to care, but three things follow from it:

  • Pending edits. getPendingCount() and hasPendingChanges() tell you whether the server has answered everything. Use them for a "Saving…" indicator.
  • Rejected edits. If the server rejects a transaction, the client removes its effect from the local value and calls onRejection. Tell the user: the edit they saw is gone.
  • Edits that partly apply. If another user removed what a command targeted, that command is skipped and the rest of the transaction applies. This is not reported as a rejection.
const document = createSyncClientDocument({
  primitive: BoardDocument,
  url,
  database: databaseId,
  collection: collectionId,
  document: documentId,
  credential,
  onRejection: (transactionId, reason, code) => {
    showToast(`An edit could not be saved: ${reason}`);
  },
});

Transactions explains the rules behind this.

Labels and origins

transaction takes an optional second argument that describes the write:

document.transaction((root) => root.fill.set("#ff0000"), {
  label: "Change fill",
  origin: "user",
});

origin is user (the default), undo, redo or system. An undo history records user writes and uses the label to name the step.

Observing transactions

onTransaction reports every transaction applied to this client's view of the document, local or remote, with the commands that took effect and the commands that exactly reverse them:

document.subscribe({
  onTransaction: (transaction) => {
    // transaction.source is "local" or "remote"
    // transaction.commands, transaction.inverse
    // transaction.actor, for a remote transaction: { kind, sub? }
  },
});

A remote transaction's actor says who wrote it, as the server verified: kind is user, key, capability or engine, and sub is the subject of the document token it was written with, when the token named one. It lets you tell an agent's edits apart from the people editing beside it.

applyCommands(commands, meta) applies commands you already have as one transaction, and applyBestEffort(commands, meta) does the same but skips commands whose target no longer exists, returning the ones that took effect. Together with onTransaction they are what the undo history is built from; most applications use the history instead of calling them directly.

Next