Client: Collections
Collections are dynamic sets of records. When you subscribe to a collection, you receive:
- A list of current record IDs
- Diffs whenever records are added or removed
- Optional updates to records within the collection
This is useful for filtered lists, dashboards, multiplayer rooms, etc.
Subscribing to a collection
Use subscribeCollection(...)
to subscribe:
const result = await client.subscribeCollection("collection:all-tasks", {
onUpdate: (recordId, update) => {
// Called when a record in the collection changes
console.log("Update for", recordId, update);
},
onDiff: (diff) => {
// Called when collection membership changes
console.log("Collection diff", diff);
},
});
You’ll get:
recordIds
: current membersversion
: starting version of the collection
The onDiff
callback is required for tracking membership. onUpdate
is optional.
Mode: “patch” vs “full”
You can control how record updates are delivered using the mode
option:
await client.subscribeCollection("collection:all-tasks", {
mode: "patch",
onUpdate: (recordId, update) => {
// patch or full update for this record
},
onDiff: (diff) => {
// added/removed recordIds
},
});
"patch"
: send JSON patches for updates (smaller, requires local state)"full"
: send full record values (simpler, larger)
Default mode is "full"
.
Handling diffs
Each time records are added or removed, onDiff(...)
is called:
(diff) => {
console.log("Added:", diff.added);
console.log("Removed:", diff.removed);
console.log("Version:", diff.version);
};
Internally, Mesh uses version tracking. If your client misses a version (e.g. network drop), Mesh automatically resyncs the full list.
Refresh manually
To force a refresh of the collection (e.g. after a user action), use:
const { added, removed, version } = await client.refreshCollection(
"collection:all-tasks"
);
This re-runs the server-side resolver and gives you the diff result.
Unsubscribing
When done, unsubscribe:
await client.unsubscribeCollection("collection:all-tasks");
This stops receiving diffs and updates for that collection.
Reconnection
Collections are automatically resubscribed on reconnect, including handlers and mode.
Notes
- Collections track
recordIds
only - You may still want to subscribe to individual records if you care about patching/version tracking
- If you don’t provide
onUpdate
, you’ll still getonDiff
notifications
Use cases
- Live filtered lists — completed vs active, by tag or assignee
- Per-user dashboards — synced queries scoped to auth context
- Multiplayer rooms — users in room, players in game
- Workspace views — synced list of active docs or projects