Socket-only collections
Some backends have no request for a list. The server sends every row over the socket, as a snapshot, and single changes after it. A snapshot sync loads a collection from those events, so queries, loading states, joins and types work as they do with a loader. This guide builds Teamboard's task board, whose server only speaks WebSocket.
- How to load a collection from a snapshot topic, with no loader.
- The difference between
listen: "mounted"andlisten: "always", and when the server sends the snapshot. - How to scope snapshots by a filter, and read a single stream of snapshots and changes.
- What a query shows on reconnect and when no snapshot arrives.
- How
findOne, joins and writes work without a request.
- The server sends the whole list over a socket and has no endpoint that returns it.
- A subscription sends the current state first and changes after it, as tRPC, GraphQL and oRPC subscriptions often do.
- You still have requests for writes, or for other collections. Loaders and snapshot syncs mix freely.
A snapshot and its changes
Teamboard's server sends tasks/snapshot with every task, then one event per change:
const onTasks = socket.createListener<{ items: Task[] }>()({
topic: "tasks/snapshot",
});
const onTaskChanged = socket.createListener<Partial<Task> & { id: string }>()({
topic: "tasks/changed",
});
const onTaskRemoved = socket.createListener<{ taskId: string }>()({
topic: "tasks/removed",
});
const Task = collection(TaskSchema, { key: "id" })
.sync(onTasks, { type: "snapshot", rows: (message) => message.items })
.sync(onTaskChanged, { type: "update" })
.sync(onTaskRemoved, { type: "delete", key: (message) => message.taskId });
export const db = createDb({ task: Task });
const { data, status } = useLiveQuery(
db.task.where((task) => eq(task.status, "open")).orderBy((task) => task.title),
);
- The query is
loadinguntil the first snapshot arrives, thenready. - The snapshot sync holds every task, so any filter, order and limit runs on the held rows.
- Each snapshot replaces the rows. A task the next snapshot leaves out is removed.
rowsreads the list from the message. Leave it out when the message is the list itself.- A message that does not map to complete rows does not compile, as with a loader.
When the server sends the snapshot
listen decides how long the sync listens. Pick it by when your server sends the snapshot:
listen | The sync listens | Use it when the server sends the snapshot |
|---|---|---|
"mounted" (default) | While a query uses it, plus gcTime after | When a client subscribes to the topic |
"always" | From createDb until db.destroy() | Once, when the socket connects |
collection(TaskSchema, { key: "id" }).sync(onTasks, {
type: "snapshot",
rows: (message) => message.items,
listen: "always",
});
A snapshot sent on connect arrives before any component mounts. With "mounted" nobody listens yet, so the query waits
for a snapshot that already passed. With "always" the rows are there, and the first render of a query is ready.
A listener only receives what arrives after it starts. Create the socket and the db in the same module, so the
"always" sync is listening when the connection opens.
One snapshot per filter
When the server keeps a topic per team, map the query's filter to the listener, as a loader does:
const onTeamTasks = socket.createListener<Task[]>()({
topic: "teams/:teamId/tasks",
});
const Task = collection(TaskSchema, { key: "id" }).sync(onTeamTasks, {
type: "snapshot",
where: { teamId: { eq: (teamId) => ({ params: { teamId } }) } },
});
db.task.where((task) => and(eq(task.teamId, "t1"), eq(task.status, "open")));
- A query has to set
teamId, or it does not compile. Each team gets its own subscription and snapshot. - A scoped snapshot replaces the rows of its team only.
listen: "always"cannot havewhere, because no query gives it the values.
One stream for snapshots and changes
Subscriptions often send the state first and changes after it, on one stream. syncChanges reads both:
type TaskEvent =
| { type: "snapshot"; items: Task[] }
| { type: "upsert"; item: Task }
| { type: "delete"; id: string };
const onTaskStream = socket.createListener<TaskEvent>()({ topic: "tasks" });
const Task = collection(TaskSchema, { key: "id" }).syncChanges(onTaskStream, {
snapshot: ({ data }) => (data.type === "snapshot" ? data.items : undefined),
changes: ({ data }) => ({
upsert: data.type === "upsert" ? [data.item] : [],
delete: data.type === "delete" ? [data.id] : [],
}),
});
snapshot returns the rows when an event is a snapshot and undefined otherwise. It takes where and listen too.
A server with one frame format
A plain WebSocket server that sends { type, payload } frames needs no syncChanges. Give each frame type its own
topic with the adapter's decode option, and declare one sync per topic:
export const socket = createSocketClient({
url: "wss://api.teamboard.dev/ws",
adapterOptions: {
decode: (event) => {
const { type, payload } = JSON.parse(event.data);
return { topic: `tasks/${type}`, data: payload };
},
},
});
Disconnects and missing snapshots
A snapshot subset is fresh while its listener is live. It never refetches because time passed.
- Disconnect: the rows stay and the query reports
stale: true. - Reconnect: the events the socket missed are unknown, so the query stays stale and
isFetchinguntil a new snapshot arrives. Setresumes: truewhen your server replays missed events, and the query is fresh at once. refetch()has nothing to fetch. It resolves at once on a fresh query, and listens again when the server ended the listener.
When the listener is live and no snapshot arrives within syncTimeout, 5 seconds by default, the query gets an error:
const { status, error } = useLiveQuery(db.task.where((task) => eq(task.status, "open")));
if (status === "error" && error instanceof SnapshotTimeoutError) {
return <p>The server sent no tasks on {error.topic}.</p>;
}
The listener stays on, and a later snapshot clears the error. Change the time with createDb(collections, { syncTimeout }).
A snapshot that cannot be read is reported to db.onError with type: "sync", and the rows the query has stay.
One row, joins and writes
A snapshot sync without where holds every row, so it also serves reads by key:
db.task.findOne("task-1"); // loading until the snapshot, then the row or undefined
db.comment.join("task", db.task, (comment) => comment.taskId); // joined rows come from the snapshot
Writes still go through requests, declared with .mutate(). The socket confirms them:
const Task = collection(TaskSchema, { key: "id" })
.sync(onTasks, { type: "snapshot", rows: (message) => message.items })
.sync(onTaskChanged, { type: "update" })
.mutate({
update: {
request: updateTask,
map: (key, changes) => ({ params: { taskId: key }, payload: changes }),
onSuccess: "sync",
},
});
onSuccess: "sync"keeps the optimistic value until an event, or a snapshot that changed the row, confirms it.onSuccess: "refetch"keeps the written values, because there is nothing to fetch.- Set
versionon the collection. Without it, a snapshot the server built before a write can show the old value for a moment.
query.explain() shows which source serves a query, and .local() reads held rows without starting a listener.
Teamboard's task board loads and stays current from a socket alone.
- You can load a collection from a snapshot topic with
type: "snapshot". - You can pick
listen: "always"for a server that sends the snapshot once on connect. - You can scope snapshots with
where, and read one stream withsyncChangesandsnapshot. - You can show stale rows on disconnect and a clear timeout error when no snapshot arrives.
- You can use
findOne, joins and optimistic writes without a list endpoint.
Next steps
- API reference:
SnapshotSyncOptions,SyncChangesOptions,SnapshotTimeoutError.