Open History to see the last commit
1---
2title: Creating a Collection Options Creator
3id: guide/collection-options-creator
4---
5A collection options creator is a factory function that generates configuration options for TanStack DB collections. It provides a standardized way to integrate different sync engines and data sources with TanStack DB's reactive sync-first architecture.
6
7## Overview
8
9Collection options creators follow a consistent pattern:
101. Accept configuration specific to the sync engine
112. Return an object that satisfies the `CollectionConfig` interface
123. Handle sync initialization, data parsing, and transaction management
134. Optionally provide utility functions specific to the sync engine
14
15## When to Create a Custom Collection
16
17You should create a custom collection when:
18- You have a dedicated sync engine (like ElectricSQL, Trailbase, Firebase, RxDB or a custom WebSocket solution)
19- You need specific sync behaviors that aren't covered by the query collection
20- You want to integrate with a backend that has its own sync protocol
21
22**Note**: If you're just hitting an API and returning data, use the query collection instead.
23
24## Core Requirements
25
26Every collection options creator must implement these key responsibilities:
27
28### 1. Configuration Interface
29
30Define a configuration interface that extends or includes standard collection properties:
31
32```typescript
33// Pattern A: User provides handlers (Query / ElectricSQL style)
34interface MyCollectionConfig<TItem extends object> {
35 // Your sync engine specific options
36 connectionUrl: string
37 apiKey?: string
39 // Standard collection properties
40 id?: string
41 schema?: StandardSchemaV1
42 getKey: (item: TItem) => string | number
43 sync?: SyncConfig<TItem>
45 rowUpdateMode?: 'partial' | 'full'
47 // User provides mutation handlers
48 onInsert?: InsertMutationFn<TItem>
49 onUpdate?: UpdateMutationFn<TItem>
50 onDelete?: DeleteMutationFn<TItem>
51}
52
53// Pattern B: Built-in handlers (Trailbase style)
54interface MyCollectionConfig<TItem extends object>
55 extends Omit<CollectionConfig<TItem>, 'onInsert' | 'onUpdate' | 'onDelete'> {
56 // Your sync engine specific options
57 recordApi: MyRecordApi<TItem>
58 connectionUrl: string
60 rowUpdateMode?: 'partial' | 'full'
62 // Note: onInsert/onUpdate/onDelete are implemented by your collection creator
63}
64```
65
66Adapter-specific properties can be returned alongside the core options. TanStack DB ignores these extra properties. Development builds warn only about likely misspellings of a core option, such as `oninsert` for `onInsert`, when the correctly named option is absent. Missing or invalid required core options still throw.
67
68Keep adapter behavior in the adapter: returning `parse` or `serialize` does not make TanStack DB apply these conversions. Apply `parse` before calling `write` in your sync implementation, and apply `serialize` in mutation handlers. Put `rowUpdateMode` inside the returned `sync` object.
69
70### 2. Sync Implementation
71
72Each call to the sync function starts a **sync run**. The run owns the callbacks
73and resources installed by that call until its returned cleanup ends them. A
74sync run may make several backend requests or open a longer-lived provider
75session, so it is not itself a request or provider session.
76
77The sync function is the heart of your collection. It must return a cleanup
78function for proper garbage collection:
79
80```typescript
81const sync: SyncConfig<T>['sync'] = (params) => {
82 const { begin, write, commit, markReady, markError, collection } = params
84 // 1. Initialize connection to your sync engine
85 const connection = initializeConnection(config)
86 const initialSyncAbort = new AbortController()
88 // 2. Set up real-time subscription FIRST (prevents race conditions)
89 const eventBuffer: Array<any> = []
90 let isInitialSyncComplete = false
92 connection.subscribe((event) => {
93 if (!isInitialSyncComplete) {
94 // Buffer events during initial sync to prevent race conditions
95 eventBuffer.push(event)
96 return
97 }
99 // Process real-time events
100 begin()
102 switch (event.type) {
103 case 'insert':
104 write({ type: 'insert', value: event.data })
105 break
106 case 'update':
107 write({ type: 'update', value: event.data })
108 break
109 case 'delete':
110 write({ type: 'delete', value: event.data })
111 break
112 }
114 commit()
115 })
117 // 3. Perform initial data fetch
118 async function initialSync() {
119 try {
120 const data = await fetchInitialData({ signal: initialSyncAbort.signal })
122 begin() // Start a transaction
124 for (const item of data) {
125 write({
126 type: 'insert',
127 value: item
128 })
129 }
131 commit() // Commit the transaction
133 // 4. Process buffered events
134 isInitialSyncComplete = true
135 if (eventBuffer.length > 0) {
136 begin()
137 for (const event of eventBuffer) {
138 // Deduplicate if necessary based on your sync engine
139 write({ type: event.type, value: event.data })
140 }
141 commit()
142 eventBuffer.splice(0)
143 }
144
145 // A complete initial snapshot is now available.
146 markReady()
147 } catch (error) {
148 if (initialSyncAbort.signal.aborted) return
149 console.error('Initial sync failed:', error)
150 // No usable initial snapshot exists.
151 // Only initial startup owns collection readiness. A later refetch
152 // failure must keep the last ready snapshot usable.
153 if (collection.status === 'loading') markError(error)
154 }
155 }
156
157 initialSync()
159 // 4. Return cleanup function
160 return () => {
161 initialSyncAbort.abort()
162 connection.close()
163 // Clean up any timers, intervals, or other resources
164 }
165}
166```
167
168### 3. Transaction Lifecycle
169
170Understanding the transaction lifecycle is important for correct implementation.
171
172The sync process follows this lifecycle:
173
1741. **begin()** - Start collecting changes
1752. **write()** - Add changes to the pending transaction (buffered until commit)
1763. **commit()** - Apply all changes atomically to the collection state
1774. **markReady()** - Signal that a usable initial or recovered snapshot exists
1785. **markError(error?)** - Signal that initial sync failed before producing a usable snapshot; pass the cause so readiness waits reject with it
179
180`commit()` accepts the transaction and returns `true`. An accepted transaction
181always applies, in commit order. While an optimistic transaction is persisting,
182the accepted transaction waits. It becomes visible when that optimistic
183transaction settles, in the same publication that drops its optimistic state.
184A mutation handler can therefore await its own write without waiting for
185itself. A wrapping sync, such as persistence, returns a promise that resolves
186after its durable step. A successful `loadSubset` must await or return every
187commit receipt that establishes its result.
188
189The collection keeps the object you pass to `write()` as the row's stored
190value. Pass a new object for each update. If your source changes a row object
191in place and writes it again, pass the row's previous value as
192`previousValue`. Without it, the change already overwrote the value the
193collection needs to publish the update, and live queries can keep the row in
194a result it left. In development, the collection throws
195`SyncRowReusedWithoutPreviousValueError` for that write when a top-level field
196changed. The check compares shallow copies, so it does not detect a change
197inside a nested object. Pass `previousValue` for those writes too.
198
199```ts
200// Changes a stored row in place, so it must name the previous value
201const previousValue = { ...row }
202row.status = `done`
203write({ type: `update`, value: row, previousValue })
204```
205
206For request-scoped writes, pass the request's abort signal to `commit(signal)`.
207If the signal has already aborted, the transaction is abandoned and the receipt
208rejects with `AbortError`. An accepted transaction ignores a later abort: its
209rows apply. To discard a stale page, check the signal before `commit()`. If the
210caller aborted after the page was accepted, the rows still apply, but reject the
211load with `AbortError` once its receipt resolves. Do not attach one request's
212signal to a shared stream transaction.
213
214If an adapter supplies `unloadSubset`, release only the acquisition belonging to
215the supplied options. Release must be idempotent and non-throwing; the adapter
216owns any remote unsubscribe retry. A synchronous `loadSubset` throw must clean
217up resources acquired before it throws. Returning a promise transfers ownership
218even if that promise later rejects, so failed acquisitions must remain safe to
219release without affecting peers.
220
221**Race Condition Prevention:**
222Many sync engines start real-time subscriptions before the initial sync completes. Your implementation MUST deduplicate events that arrive via subscription that represent the same data as the initial sync. Consider:
223- Starting the listener BEFORE initial fetch and buffering events
224- Tracking timestamps, sequence numbers, or document versions
225- Using read timestamps or other ordering mechanisms
226
227### 4. Data Parsing and Type Conversion
228
229If your sync engine returns data with different types, provide conversion functions for specific fields:
230
231```typescript
232interface MyCollectionConfig<TItem, TRecord> {
233 // ... other config
235 // Only specify conversions for fields that need type conversion
236 parse: {
237 created_at: (ts: number) => new Date(ts * 1000), // timestamp -> Date
238 updated_at: (ts: number) => new Date(ts * 1000), // timestamp -> Date
239 metadata?: (str: string) => JSON.parse(str) // JSON string -> object
240 }
242 serialize: {
243 created_at: (date: Date) => Math.floor(date.valueOf() / 1000), // Date -> timestamp
244 updated_at: (date: Date) => Math.floor(date.valueOf() / 1000), // Date -> timestamp
245 metadata?: (obj: object) => JSON.stringify(obj) // object -> JSON string
246 }
247}
248```
249
250**Type Conversion Examples:**
251```typescript
252// Firebase Timestamp to Date
253parse: {
254 createdAt: (timestamp) => timestamp?.toDate?.() || new Date(timestamp),
255 updatedAt: (timestamp) => timestamp?.toDate?.() || new Date(timestamp),
256}
257
258// PostGIS geometry to GeoJSON
259parse: {
260 location: (wkb: string) => parseWKBToGeoJSON(wkb)
261}
262
263// JSON string to object with error handling
264parse: {
265 metadata: (str: string) => {
266 try {
267 return JSON.parse(str)
268 } catch {
269 return {}
270 }
271 }
272}
273```
274
275### 5. Schemas and Type Transformations
276
277When building a custom collection, you need to decide how to handle the relationship between your backend's storage format and the client-side types users work with in their collections.
278
279#### Two Separate Concerns
280
281**Backend Format** - The types your storage layer uses (SQLite, Postgres, Firebase, etc.)
282- Examples: Unix timestamps, ISO strings, JSON strings, PostGIS geometries
283
284**Client Format** - The types users work with in their TanStack DB collections
285- Examples: Date objects, parsed JSON, GeoJSON
286
287Schemas in TanStack DB define the **client format** (TInput/TOutput for mutations). How you bridge between backend and client format depends on your integration design.
288
289#### Approach 1: Integration Provides Parse/Serialize Helpers
290
291For backends with specific storage formats, provide `parse`/`serialize` options that users configure:
292
293```typescript
294// TrailBase example: User specifies field conversions
295export function trailbaseCollectionOptions(config) {
296 return {
297 // ... getKey, schema, and sync options
298 // The sync implementation applies config.parse before calling write.
299
300 onInsert: async ({ transaction }) => {
301 const serialized = transaction.mutations.map(m =>
302 serializeFields(m.modified, config.serialize)
303 )
304 await config.recordApi.createBulk(serialized)
305 }
306 }
307}
308
309// User explicitly configures conversions
310const collection = createCollection(
311 trailbaseCollectionOptions({
312 schema: todoSchema,
313 parse: {
314 created_at: (ts: number) => new Date(ts * 1000) // Unix → Date
315 },
316 serialize: {
317 created_at: (date: Date) => Math.floor(date.valueOf() / 1000) // Date → Unix
318 }
319 })
320)
321```
322
323**Benefits:** Explicit control over type conversions. Integration handles applying them consistently.
324
325#### Approach 2: User Handles Everything in QueryFn/Handlers
326
327For simple APIs or when users want full control, they handle parsing/serialization themselves:
328
329```typescript
330// Query Collection: User handles all transformations
331const collection = createCollection(
332 queryCollectionOptions({
333 schema: todoSchema,
334 queryFn: async () => {
335 const response = await fetch('/api/todos')
336 const todos = await response.json()
337 // User manually parses to match their schema's TOutput
338 return todos.map(todo => ({
339 ...todo,
340 created_at: new Date(todo.created_at) // ISO string → Date
341 }))
342 },
343 onInsert: async ({ transaction }) => {
344 // User manually serializes for their backend
345 await fetch('/api/todos', {
346 method: 'POST',
347 body: JSON.stringify({
348 ...transaction.mutations[0].modified,
349 created_at: transaction.mutations[0].modified.created_at.toISOString() // Date → ISO string
350 })
351 })
352 }
353 })
354)
355```
356
357**Benefits:** Maximum flexibility, no abstraction overhead. Users see exactly what's happening.
358
359#### Approach 3: Automatic Serialization in Handlers
360
361If your backend has well-defined types, you can automatically serialize in mutation handlers:
362
363```typescript
364export function myCollectionOptions(config) {
365 return {
366 onInsert: async ({ transaction }) => {
367 // Automatically serialize known types for your backend
368 const serialized = transaction.mutations.map(m => ({
369 ...m.modified,
370 // Date objects → Unix timestamps for your backend
371 created_at: m.modified.created_at instanceof Date
372 ? Math.floor(m.modified.created_at.valueOf() / 1000)
373 : m.modified.created_at
374 }))
375 await backend.insert(serialized)
376 }
377 }
378}
379```
380
381**Benefits:** Least configuration for users. Integration handles backend format automatically.
382
383#### Key Design Principles
384
3851. **Schemas validate client mutations only** - They don't affect how backend data is parsed during sync
3862. **TOutput is the application-facing type** - This is what users work with in their app
3873. **Choose your approach based on backend constraints** - Fixed types → automatic serialization; varying types → user configuration
3884. **Document your backend format clearly** - Explain what types your storage uses and how to handle them
389
390For more on schemas from a user perspective, see the [Schemas guide](./schemas.md).
391
392### 6. Mutation Handler Patterns
393
394There are two distinct patterns for handling mutations in collection options creators:
395
396#### Pattern A: User-Provided Handlers (Query, Standard)
397
398The user provides mutation handlers in the config. Your collection creator passes them through.
399
400**Note:** Handler return values are deprecated. Users should trigger refetch/sync within their handlers.
401
402```typescript
403interface MyCollectionConfig<TItem extends object> {
404 // ... other config
405
406 // User provides these handlers
407 onInsert?: InsertMutationFn<TItem>
408 onUpdate?: UpdateMutationFn<TItem>
409 onDelete?: DeleteMutationFn<TItem>
410}
411
412export function myCollectionOptions<TItem extends object>(
413 config: MyCollectionConfig<TItem>
414) {
415 return {
416 // ... other options
417 sync: {
418 sync: syncFn,
419 rowUpdateMode: config.rowUpdateMode ?? 'partial'
420 },
421
422 // Pass through user-provided handlers
423 // Users handle sync coordination in their own handlers
424 onInsert: config.onInsert,
425 onUpdate: config.onUpdate,
426 onDelete: config.onDelete
427 }
428}
429```
430
431
432#### Pattern B: Built-in Handlers (Trailbase, WebSocket, Firebase)
433
434Your collection creator implements the handlers directly using the sync engine's APIs:
435
436```typescript
437interface MyCollectionConfig<TItem extends object>
438 extends Omit<CollectionConfig<TItem>, 'onInsert' | 'onUpdate' | 'onDelete'> {
439 // ... sync engine specific config
440 // Note: onInsert/onUpdate/onDelete are NOT in the config
441}
442
443export function myCollectionOptions<TItem extends object>(
444 config: MyCollectionConfig<TItem>
445) {
446 return {
447 // ... other options
448 sync: {
449 sync: syncFn,
450 rowUpdateMode: config.rowUpdateMode ?? 'partial'
451 },
452
453 // Implement handlers using sync engine APIs
454 onInsert: async ({ transaction }) => {
455 // Handle provider-specific batch limits (e.g., Firestore's 500 limit)
456 const chunks = chunkArray(transaction.mutations, PROVIDER_BATCH_LIMIT)
457
458 for (const chunk of chunks) {
459 const ids = await config.recordApi.createBulk(
460 chunk.map(m => serialize(m.modified))
461 )
462 // Wait for these IDs to sync back before completing
463 await awaitIds(ids)
464 }
465 // Handler completes after sync coordination
466 },
467
468 onUpdate: async ({ transaction }) => {
469 const chunks = chunkArray(transaction.mutations, PROVIDER_BATCH_LIMIT)
470
471 for (const chunk of chunks) {
472 await Promise.all(
473 chunk.map(m =>
474 config.recordApi.update(m.key, serialize(m.changes))
475 )
476 )
477 }
478
479 // Wait for mutations to sync back
480 await awaitIds(transaction.mutations.map(m => String(m.key)))
481 }
482 }
483}
484```
485
486Many providers have batch size limits (Firestore: 500, DynamoDB: 25, etc.) so chunk large transactions accordingly.
487
488**Key Principle:** Built-in handlers should coordinate sync internally (using `awaitIds`, `awaitTxId`, or similar) and not rely on return values. The handler completes only after sync coordination is done.
489
490Choose Pattern A when users need to provide their own APIs, and Pattern B when your sync engine handles writes directly.
491
492## Row Update Modes
493
494Collections support two update modes:
495
496- **`partial`** (default) - Updates are merged with existing data
497- **`full`** - Updates replace the entire row
498
499Configure this in your sync config:
500
501```typescript
502sync: {
503 sync: syncFn,
504 rowUpdateMode: 'full' // or 'partial'
505}
506```
507
508## Production Examples
509
510For complete, production-ready examples, see the collection packages in the TanStack DB repository:
511
512- **[@tanstack/query-db-collection](https://github.com/TanStack/db/tree/main/packages/query-db-collection)** - Pattern A: User-provided handlers with full refetch strategy
513- **[@tanstack/trailbase-db-collection](https://github.com/TanStack/db/tree/main/packages/trailbase-db-collection)** - Pattern B: Built-in handlers with ID-based tracking
514- **[@tanstack/electric-db-collection](https://github.com/TanStack/db/tree/main/packages/electric-db-collection)** - Pattern A: Transaction ID tracking with complex sync protocols
515- **[@tanstack/rxdb-db-collection](https://github.com/TanStack/db/tree/main/packages/rxdb-db-collection)** - Pattern B: Built-in handlers that bridge [RxDB](https://rxdb.info) change streams into TanStack DB's sync lifecycle
516
517### Key Lessons from Production Collections
518
519**From Query Collection:**
520- Simplest approach: Full refetch after mutations
521- Best for: APIs without real-time sync
522- Pattern: User provides `onInsert/onUpdate/onDelete` handlers
523
524**From Trailbase Collection:**
525- Shows ID-based optimistic state management
526- Handles provider batch limits (chunking large operations)
527- Pattern: Collection provides mutation handlers using record API
528
529**From Electric Collection:**
530- Complex transaction ID tracking for distributed sync
531- Demonstrates advanced deduplication techniques
532- Shows how to wrap user handlers with sync coordination
533
534**From RxDB Collection:**
535- Uses RxDB's built-in queries and change streams
536- Uses `RxCollection.$` to subscribe to inserts/updates/deletes and forward them to TanStack DB with begin-write-commit
537- Implements built-in mutation handlers (onInsert, onUpdate, onDelete) that call RxDB APIs (bulkUpsert, incrementalPatch, bulkRemove)
538
539## Complete Example: WebSocket Collection
540
541Here's a complete example of a WebSocket-based collection options creator that demonstrates the full round-trip flow:
542
5431. Client sends transaction with all mutations batched together
5442. Server processes the transaction and may modify the data (validation, timestamps, etc.)
5453. Server sends back acknowledgment and the actual processed data
5464. Client waits for this round-trip before dropping optimistic state
547
548```typescript
549import type {
550 CollectionConfig,
551 SyncConfig,
552 InsertMutationFnParams,
553 UpdateMutationFnParams,
554 DeleteMutationFnParams,
555 UtilsRecord
556} from '@tanstack/db'
557
558interface WebSocketMessage<T> {
559 type: 'insert' | 'update' | 'delete' | 'sync' | 'transaction' | 'ack'
560 data?: T | T[]
561 mutations?: Array<{
562 type: 'insert' | 'update' | 'delete'
563 data: T
564 id?: string
565 }>
566 transactionId?: string
567 id?: string
568}
569
570interface WebSocketCollectionConfig<TItem extends object>
571 extends Omit<CollectionConfig<TItem>, 'onInsert' | 'onUpdate' | 'onDelete' | 'sync'> {
572 url: string
573 reconnectInterval?: number
575 // Note: onInsert/onUpdate/onDelete are handled by the WebSocket connection
576 // Users don't provide these handlers
577}
578
579interface WebSocketUtils extends UtilsRecord {
580 reconnect: () => void
581 getConnectionState: () => 'connected' | 'disconnected' | 'connecting'
582}
583
584export function webSocketCollectionOptions<TItem extends object>(
585 config: WebSocketCollectionConfig<TItem>
586): CollectionConfig<TItem> & { utils: WebSocketUtils } {
587 let ws: WebSocket | null = null
588 let reconnectTimer: NodeJS.Timeout | null = null
589 let connectionState: 'connected' | 'disconnected' | 'connecting' = 'disconnected'
591 // Track pending transactions awaiting acknowledgment
592 const pendingTransactions = new Map<string, {
593 resolve: () => void
594 reject: (error: Error) => void
595 timeout: NodeJS.Timeout
596 }>()
598 const sync: SyncConfig<TItem>['sync'] = (params) => {
599 const { begin, write, commit, markReady } = params
601 function connect() {
602 connectionState = 'connecting'
603 ws = new WebSocket(config.url)
605 ws.onopen = () => {
606 connectionState = 'connected'
607 // Request initial sync
608 ws.send(JSON.stringify({ type: 'sync' }))
609 }
611 ws.onmessage = (event) => {
612 const message: WebSocketMessage<TItem> = JSON.parse(event.data)
614 switch (message.type) {
615 case 'sync':
616 // Initial sync with array of items
617 begin()
618 if (Array.isArray(message.data)) {
619 for (const item of message.data) {
620 write({ type: 'insert', value: item })
621 }
622 }
623 commit()
624 markReady()
625 break
627 case 'insert':
628 case 'update':
629 case 'delete':
630 // Real-time updates from other clients
631 begin()
632 write({
633 type: message.type,
634 value: message.data as TItem
635 })
636 commit()
637 break
639 case 'ack':
640 // Server acknowledged our transaction
641 if (message.transactionId) {
642 const pending = pendingTransactions.get(message.transactionId)
643 if (pending) {
644 clearTimeout(pending.timeout)
645 pendingTransactions.delete(message.transactionId)
646 pending.resolve()
647 }
648 }
649 break
651 case 'transaction':
652 // Server sending back the actual data after processing our transaction
653 if (message.mutations) {
654 begin()
655 for (const mutation of message.mutations) {
656 write({
657 type: mutation.type,
658 value: mutation.data
659 })
660 }
661 commit()
662 }
663 break
664 }
665 }
667 ws.onerror = (error) => {
668 console.error('WebSocket error:', error)
669 connectionState = 'disconnected'
670 }
672 ws.onclose = () => {
673 connectionState = 'disconnected'
674 // Auto-reconnect
675 if (!reconnectTimer) {
676 reconnectTimer = setTimeout(() => {
677 reconnectTimer = null
678 connect()
679 }, config.reconnectInterval || 5000)
680 }
681 }
682 }
684 // Start connection
685 connect()
687 // Return cleanup function
688 return () => {
689 if (reconnectTimer) {
690 clearTimeout(reconnectTimer)
691 reconnectTimer = null
692 }
693 if (ws) {
694 ws.close()
695 ws = null
696 }
697 }
698 }
700 // Helper function to send transaction and wait for server acknowledgment
701 const sendTransaction = async (
702 params: InsertMutationFnParams<TItem> | UpdateMutationFnParams<TItem> | DeleteMutationFnParams<TItem>
703 ): Promise<void> => {
704 if (ws?.readyState !== WebSocket.OPEN) {
705 throw new Error('WebSocket not connected')
706 }
708 const transactionId = crypto.randomUUID()
710 // Convert all mutations in the transaction to the wire format
711 const mutations = params.transaction.mutations.map(mutation => ({
712 type: mutation.type,
713 id: mutation.key,
714 data: mutation.type === 'delete' ? undefined :
715 mutation.type === 'update' ? mutation.changes :
716 mutation.modified
717 }))
719 // Send the entire transaction at once
720 ws.send(JSON.stringify({
721 type: 'transaction',
722 transactionId,
723 mutations
724 }))
726 // Wait for server acknowledgment
727 return new Promise<void>((resolve, reject) => {
728 const timeout = setTimeout(() => {
729 pendingTransactions.delete(transactionId)
730 reject(new Error(`Transaction ${transactionId} timed out`))
731 }, 10000) // 10 second timeout
733 pendingTransactions.set(transactionId, {
734 resolve,
735 reject,
736 timeout
737 })
738 })
739 }
741 // All mutation handlers use the same transaction sender
742 // Handlers wait for server acknowledgment before completing
743 const onInsert = async (params: InsertMutationFnParams<TItem>): Promise<void> => {
744 await sendTransaction(params)
745 // Handler completes after server confirms the transaction
746 }
747
748 const onUpdate = async (params: UpdateMutationFnParams<TItem>): Promise<void> => {
749 await sendTransaction(params)
750 }
751
752 const onDelete = async (params: DeleteMutationFnParams<TItem>): Promise<void> => {
753 await sendTransaction(params)
754 }
756 return {
757 id: config.id,
758 schema: config.schema,
759 getKey: config.getKey,
760 sync: { sync },
761 onInsert,
762 onUpdate,
763 onDelete,
764 utils: {
765 reconnect: () => {
766 if (ws) ws.close()
767 connect()
768 },
769 getConnectionState: () => connectionState
770 }
771 }
772}
773```
774
775## Usage Example
776
777```typescript
778import { DbClient, collectionOptions } from '@tanstack/react-db'
779import { webSocketCollectionOptions } from './websocket-collection'
780
781const db = new DbClient()
782
783const todosCollection = collectionOptions('todos', () =>
784 webSocketCollectionOptions({
785 id: 'todos',
786 url: 'ws://localhost:8080/todos',
787 getKey: (todo) => todo.id,
788 schema: todoSchema,
789 // Note: No onInsert/onUpdate/onDelete - handled by WebSocket automatically
790 })
791)
792
793const todos = db.collection(todosCollection)
794
795// Use the collection
796todos.insert({ id: '1', text: 'Buy milk', completed: false })
797
798// Access utilities
799todos.utils.getConnectionState() // 'connected'
800todos.utils.reconnect() // Force reconnect
801```
802
803## Advanced: Managing Optimistic State
804
805A critical challenge in sync-first apps is knowing when to drop optimistic state. When a user makes a change:
806
8071. The UI updates immediately (optimistic update)
8082. A mutation is sent to the backend
8093. The backend processes and persists the change
8104. The change syncs back to the client
8115. The optimistic state should be dropped in favor of the synced data
812
813The key question is: **How do you know when step 4 is complete?**
814
815### Strategy 1: Built-in Provider Methods (Recommended)
816
817Many providers offer built-in methods to wait for sync completion:
818
819```typescript
820// Firebase
821await waitForPendingWrites(firestore)
822
823// Custom WebSocket
824await websocket.waitForAck(transactionId)
825```
826
827### Strategy 2: Transaction ID Tracking (ElectricSQL)
828
829ElectricSQL returns transaction IDs that you can track:
830
831```typescript
832// Track seen transaction IDs
833const seenTxids = new Store<Set<number>>(new Set())
834
835// In sync, track txids from incoming messages
836if (message.headers.txids) {
837 message.headers.txids.forEach(txid => {
838 seenTxids.setState(prev => new Set([...prev, txid]))
839 })
840}
841
842// Electric-specific: expose awaitTxId through collection.utils so handlers
843// can coordinate txid-based sync before they complete
844const wrappedOnInsert = async (params) => {
845 // The user handler persists the mutation, then calls
846 // await params.collection.utils.awaitTxId(txid) internally.
847 await config.onInsert!(params)
848}
849
850// Utility function to wait for a txid
851const awaitTxId = (txId: number): Promise<boolean> => {
852 if (seenTxids.state.has(txId)) return Promise.resolve(true)
854 return new Promise((resolve) => {
855 const unsubscribe = seenTxids.subscribe(() => {
856 if (seenTxids.state.has(txId)) {
857 unsubscribe()
858 resolve(true)
859 }
860 })
861 })
862}
863```
864
865### Strategy 3: ID-Based Tracking (Trailbase)
866
867Trailbase tracks when specific record IDs have been synced:
868
869```typescript
870// Track synced IDs with timestamps
871const seenIds = new Store(new Map<string, number>())
872
873// In sync, mark IDs as seen
874write({ type: 'insert', value: item })
875seenIds.setState(prev => new Map(prev).set(item.id, Date.now()))
876
877// Wait for specific IDs after mutations
878const wrappedOnInsert = async (params) => {
879 const ids = await config.recordApi.createBulk(items)
880
881 // Wait for all IDs to be synced back before handler completes
882 await awaitIds(ids)
883}
884
885const awaitIds = (ids: string[]): Promise<void> => {
886 const allSynced = ids.every(id => seenIds.state.has(id))
887 if (allSynced) return Promise.resolve()
889 return new Promise((resolve) => {
890 const unsubscribe = seenIds.subscribe((state) => {
891 if (ids.every(id => state.has(id))) {
892 unsubscribe()
893 resolve()
894 }
895 })
896 })
897}
898```
899
900### Strategy 4: Version/Timestamp Tracking
901
902Track version numbers or timestamps to detect when data is fresh:
903
904```typescript
905// Track latest sync timestamp
906let lastSyncTime = 0
907
908// In mutations, record when the operation was sent
909const wrappedOnUpdate = async (params) => {
910 const mutationTime = Date.now()
911 await config.onUpdate(params)
912
913 // Wait for sync to catch up before handler completes
914 await waitForSync(mutationTime)
915}
916
917const waitForSync = (afterTime: number): Promise<void> => {
918 if (lastSyncTime > afterTime) return Promise.resolve()
920 return new Promise((resolve) => {
921 const check = setInterval(() => {
922 if (lastSyncTime > afterTime) {
923 clearInterval(check)
924 resolve()
925 }
926 }, 100)
927 })
928}
929```
930
931### Strategy 5: Refetch (Query Collection)
932
933The query collection pattern has users refetch after mutations:
934
935```typescript
936// Pattern A: User provides handlers and manages refetch
937export function queryCollectionOptions<TItem>(config) {
938 return {
939 // ... other options
940
941 // User provides handlers and they handle refetch themselves
942 onInsert: config.onInsert, // User calls collection.utils.refetch() in their handler
943 onUpdate: config.onUpdate,
944 onDelete: config.onDelete,
945
946 utils: {
947 refetch: () => {
948 // Refetch implementation that syncs fresh data
949 // automatically dropping optimistic state
950 }
951 }
952 }
953}
954
955// Usage: User refetches in their handler
956const collection = createCollection(
957 queryCollectionOptions({
958 onInsert: async ({ transaction, collection }) => {
959 await api.createTodos(transaction.mutations.map(m => m.modified))
960 // User explicitly triggers refetch
961 await collection.utils.refetch()
962 // Prevent the pre-1.0 compatibility wrapper from refetching again.
963 return { refetch: false }
964 }
965 })
966)
967```
968
969### Choosing a Strategy
970
971- **Built-in Methods**: Best when your provider offers sync completion APIs
972- **Transaction IDs**: Best when your backend provides reliable transaction tracking
973- **ID-Based**: Good for systems where each mutation returns the affected IDs
974- **Full Refetch**: Simplest but least efficient; good for small datasets
975- **Version/Timestamp**: Works when your sync includes reliable ordering information
976
977### Implementation Tips
978
9791. **Always wait for sync** in your mutation handlers to ensure optimistic state is properly managed
9802. **Handle timeouts** - Don't wait forever for sync confirmation
9813. **Clean up tracking data** - Remove old txids/IDs to prevent memory leaks
9824. **Provide utilities** - Export functions like `awaitTxId` or `awaitSync` for advanced use cases
983
984## Best Practices
985
9861. **Report initial sync status** - Call `markReady()` after a usable snapshot, or `markError(error)` if initial sync fails
9872. **Recover explicitly** - After an error, call `markReady()` only when a later sync has produced a usable snapshot
9883. **Clean up resources** - Return a cleanup function from sync to prevent memory leaks
9894. **Batch operations** - Use begin/commit to batch multiple changes for better performance
9905. **Race Conditions** - Start listeners before initial fetch and buffer events
9916. **Type safety** - Use TypeScript generics to maintain type safety throughout
9927. **Provide utilities** - Export sync-engine-specific utilities for advanced use cases
9938. **Handler return values are deprecated** - Mutation handlers should coordinate sync internally (via `await`) rather than returning values. For Electric collections, use `await collection.utils.awaitTxId(txid)` instead of returning the txid
994
995## Testing Your Collection
996
997Test your collection options creator with:
998
9991. **Unit tests** - Test sync logic, data transformations
10002. **Integration tests** - Test with real sync engine
10013. **Error scenarios** - Connection failures, invalid data
10024. **Performance** - Large datasets, frequent updates
1003
1004## Conclusion
1005
1006Creating a collection options creator allows you to integrate any sync engine with TanStack DB's powerful sync-first architecture. Follow the patterns shown here, and you'll have a robust, type-safe integration that provides excellent developer experience.