Skip to content

Build

Clients and React

The getting started counter uses a browser binding with volatile storage. This guide adds persistence and recovery, and shows how to open a client without React.

Define your bindings once. Their connections live in the Atom registry, so dispose the registry before switching actors. actorId selects the local session and must match the signed-in actor; it does not authenticate requests. The server still verifies the connection.

To retain pending edits across reloads, install the IndexedDB adapter:

bun add @yielded/sync-local-indexeddb

Then use its Layer in counter-atoms.ts:

counter-atoms.ts
import { IndexedDb } from "@yielded/sync-local-indexeddb";
import { BrowserSource } from "@yielded/sync-platform-browser";
import { CounterId } from "./counter";
import { CounterClient } from "./counter-client";
export const counter = BrowserSource.bind(CounterClient, {
id: CounterId.make("demo"),
actorId: "alice",
persistence: IndexedDb.layer({ namespace: "counter" }),
});

Use your signed-in actor’s ID. BrowserSource.bind supplies it to the Layer. Keep the namespace stable, and close the session before changing actors or storage. With "volatile" persistence, pending edits do not survive a reload. IndexedDB uses Web Locks to allow one active coordinator per namespace, actor, and source. A second tab with the same identity fails until the first closes its source. Web Locks require a secure browser context.

Stored data What it is for
Pending-command journal Retrying unresolved edits with their original identity
Snapshot cache Showing the last known state while reconnecting

Never delete the journal to repair a cache: it holds the information needed to retry unresolved edits. Storage errors, such as a browser quota or permission failure, can prevent new edits. Persistent mode does not silently switch to volatile mode.

Use counter.fn to combine actions with other atoms. Here the draft clears after the edit is saved locally, even while offline with a restored source:

import { Atom } from "effect/reactivity";
import { counter } from "./counter-atoms";
export const draft = Atom.make(0);
export const save = counter.fn(function* () {
const value = yield* Atom.get(draft);
yield* counter.enqueue.set({ value });
yield* Atom.set(draft, 0);
});

Use useAtom(save) in React. enqueue.set returns the admitted command’s ID; use counter.action.set when the workflow needs the server’s result instead. Keep counter.replica mounted to own background delivery. The optimistic reducer updates the view while the command is pending. Admission requires cached or live authority and retains the same storage and capacity checks as headless clients.

For an app without React, compose the transport and actor services directly. Keep the client and its lease inside an Effect scope:

import { Client } from "@yielded/sync/client";
import { Effect, Layer } from "effect";
import * as Socket from "effect/socket/Socket";
import { CounterClient } from "./counter-client";
import { Counter, CounterId } from "./counter";
const id = CounterId.make("demo");
const transport = Client.layerWebSocketTransport(Counter, {
origin: "https://app.example.com",
id,
}).pipe(Layer.provide(Socket.layerWebSocketConstructorGlobal));
export const setCounter = Effect.gen(function* () {
const session = yield* Client.make(CounterClient, { persistence: { mode: "volatile" } });
const lease = yield* session.open(Counter.address(id));
yield* lease.ready;
return yield* lease.execute(Counter.actions.set, { value: 7 });
}).pipe(
Effect.provide(transport),
Effect.provideService(Client.CurrentActor, { actorId: "alice" }),
Effect.scoped,
);

This Effect returns { previous, current } and closes the connection when it finishes. Persistent headless sessions use { mode: "persistent" } and require a ReplicaPersistence Layer for that actor.

Select values from an open lease without opening another connection:

const value = lease.select((counter) => counter.value);
const confirmed = lease.select((counter) => counter.value, { from: "authoritative" });
value.read; // Effect<Option<number>, ClientError>
value.changes; // Stream<Option<number>, ClientError>

None means unavailable; a selected undefined remains Some(undefined). Streams emit the current selection and distinct observed values, using Object.is unless you supply equals. The default includes provisional data and optimistic edits; authoritative uses the last known server state, even offline. Use lease.selectPlugin(id, selector, options?) for a declared plugin. Selections share the lease lifetime; connection status, pending commands, and failures remain on lease.read and lease.changes.

Use transitions for an incremental index or inspector that needs intermediate changes. Pass the open lease from the same scope:

import { Client } from "@yielded/sync/client";
import { Stream } from "effect";
import { Counter } from "./counter";
import { applyTransition, rebuildFrom } from "./counter-index";
export const observe = (lease: Client.Lease<typeof Counter.spec>) =>
lease
.transitions({ capacity: 256 })
.pipe(
Stream.runForEach((transition) =>
transition._tag === "Reset" ? rebuildFrom(transition.replica) : applyTransition(transition),
),
);

The first item establishes a replica baseline. Each later item captures its resulting replica; changes streams instead provide current views and may skip intermediate values. A slow transition consumer gets an explicit reset when its queue overflows. Snapshots and replay also reset the baseline, so rebuilding must replace the derived state. Closing the lease releases its subscriptions.

Live commits contain a complete action’s events. Local admission, settlement, and status changes are separate observations; a result can arrive before its events. This bounded stream cannot recover lost history across resets or reloads. Use the server outbox for durable server-side processing.

The WebSocket transport derives the path from Counter and encodes the ID. Browser bindings use the page origin by default; use origin and query to change the connection settings. Your app supplies any credentials. This transport serves one source address; apps with multiple addresses need a routing transport. See the transport API for custom URLs and RPC composition.

A lost response does not mean the edit failed:

  1. Client

    Send command c1

  2. Sync server

    Commit the edit and its receipt

    The response is lost.

  3. Client

    Look up command c1

  4. Sync server

    Return the original result

    The edit is not applied again.

Headless operation When to use it
lease.execute(action, payload) Submit an edit and wait for its result
lease.enqueue(action, payload) Return its ID after local admission; deliver in the background
lease.submit(action, payload) Return a typed command handle after local admission
lease.restore(action, id) Restore a typed handle from retained command evidence
lease.retry(commandId) Recover an uncertain result using the original command
lease.recover Restart a parked connection

Use a command handle when you need the chosen action’s result type after admission:

const command = yield * lease.submit(Counter.actions.set, { value: 7 });
const savedId = command.id;
const statuses = command.changes;
const result = yield * command.awaitResult; // { previous: number, current: number }
const recovered = yield * command.retry;
// After reopening the lease, validate the retained command against this action.
const restored = yield * lease.restore(Counter.actions.set, savedId);

submit shares enqueue’s admission and background delivery. Waiting for a result does not request another attempt; retry does exact recovery. Statuses are Pending, ConfirmedAwaitingResult, Succeeded, or Rejected; updates may coalesce and the stream completes at the outcome. Handles belong to their lease.

Restoration requires local evidence: wrong actions fail with InvalidValue, quarantined rows with Quarantined, and missing or evicted evidence with NotPending. Pending journals survive reload; completed results have only bounded retention, so saving an id does not guarantee the result can be restored later.

enqueue needs a known server authority, which can come from a restored cache. The returned ID means the edit was admitted locally; it does not mean the server accepted it. Watch pending, failures, and error on the replica. React bindings expose retry and recover atoms for the same recovery operations. Each pending command’s recovery reports attempts, lastError, and automaticRetryExhausted. Exhaustion requires manual retry even if the connection is live. These diagnostics reset on explicit recover and are not persisted.

An uncertain ClientError carries its commandId. Retry that ID rather than submitting a new edit. If a result expires or the server authority changes, keep the unresolved command so your application can reconcile it. Dismissing a terminal failure with dismissFailure does not resolve uncertain work.

Cancelling an action stops its caller, not an admitted command. Replaceable edits need an application conflict policy: the board example carries the observed title revision, omits stale optimism, and rejects stale renames on the server. Additive commands such as increments should retain each independent intent.

See the client API for connection limits and retry defaults. The React board also shows presence, persistent sessions, concurrent actions, and UI recovery.