Open History to see the last commit
1---
2title: Error Handling
3id: error-handling
4---
5
6TanStack DB provides comprehensive error handling capabilities to ensure robust data synchronization and state management. This guide covers the built-in error handling mechanisms and how to work with them effectively.
7
8## Error Types
9
10TanStack DB provides named error classes for better error handling and type safety. All error classes can be imported from `@tanstack/db` (or more commonly, the framework-specific package e.g. `@tanstack/react-db`):
11
12```ts
13import {
14 SchemaValidationError,
15 CollectionInErrorStateError,
16 DuplicateKeyError,
17 MissingHandlerError,
18 TransactionError,
19 // ... and many more
20} from "@tanstack/db"
21```
22
23### SchemaValidationError
24
25Thrown when data doesn't match the collection's schema during insert or update operations:
26
27```ts
28import { SchemaValidationError } from "@tanstack/db"
29
30try {
31 todoCollection.insert({ text: 123 }) // Invalid type
32} catch (error) {
33 if (error instanceof SchemaValidationError) {
34 console.log(error.type) // 'insert' or 'update'
35 console.log(error.issues) // Array of validation issues
36 // Example issue: { message: "Expected string, received number", path: ["text"] }
37 }
38}
39```
40
41The error includes:
42- `type`: Whether it was an 'insert' or 'update' operation
43- `issues`: Array of validation issues with messages and paths
44- `message`: A formatted error message listing all issues
45
46**When schema validation occurs:**
47
48Schema validation happens only for **client mutations** - when you explicitly insert or update data:
49
501. **During inserts** - When `collection.insert()` is called
512. **During updates** - When `collection.update()` is called
52
53Schemas do **not** validate data coming from your server or sync layer. That data is assumed to already be valid.
54
55```typescript
56const schema = z.object({
57 id: z.string(),
58 created_at: z.string().transform(val => new Date(val))
59 // TInput: string, TOutput: Date
60})
61
62// Validation happens here ✓
63collection.insert({
64 id: "1",
65 created_at: "2024-01-01" // TInput: string
66})
67// If successful, stores: { created_at: Date } // TOutput: Date
68```
69
70For more details on schema validation and type transformations, see the [Schemas guide](./schemas.md).
71
72## Query Collection Error Tracking
73
74Query collections provide enhanced error tracking utilities through the `utils` object. These methods expose error state information and provide recovery mechanisms for failed queries:
75
76```tsx
77import { createCollection } from "@tanstack/db"
78import { queryCollectionOptions } from "@tanstack/query-db-collection"
79import { useLiveQuery } from "@tanstack/react-db"
80
81const syncedCollection = createCollection(
82 queryCollectionOptions({
83 queryClient,
84 queryKey: ['synced-data'],
85 queryFn: fetchData,
86 getKey: (item) => item.id,
87 })
88)
89
90// Component can check error state
91function DataList() {
92 const { data } = useLiveQuery({
93 query: (q) => q.from({ item: syncedCollection }),
94 })
95 const isError = syncedCollection.utils.isError
96 const errorCount = syncedCollection.utils.errorCount
98 return (
99 <>
100 {isError && errorCount > 3 && (
101 <Alert>
102 Unable to sync. Showing cached data.
103 <button onClick={() => syncedCollection.utils.clearError()}>
104 Retry
105 </button>
106 </Alert>
107 )}
108 {/* Render data */}
109 </>
110 )
111}
112```
113
114Error tracking methods:
115- **`lastError`**: Returns the most recent error encountered by the query, or `undefined` if no errors have occurred since a successful result applied:
116- **`isError`**: Returns a boolean indicating whether the collection is currently in an error state:
117- **`errorCount`**: Returns the number of consecutive sync failures. This counter is incremented only when queries fail completely (not per retry attempt) and is reset after a successful result applies:
118- **`clearError()`**: Triggers a refetch. The current error remains visible until a successful result applies to the Collection. An applied result clears `lastError` and resets `errorCount`; a failed retry records another consecutive failure and rejects the returned promise. During a mutation handler, the promise can resolve at the fetch boundary before application clears the error:
119
120 ```text
121 error visible → clearError() → retry pending, error still visible
122 ├─ applied success → error cleared
123 └─ failure → new error visible, count increased
124 ```
125
126## Incremental Subset Load Errors
127
128An incremental `loadSubset` failure does not discard rows that are already
129available or put the shared source collection into `error`. The failure belongs
130to the subscription that requested that subset:
131
132```ts
133const subscription = todoCollection.subscribeChanges(handleChanges, {
134 includeInitialState: false,
135})
136
137subscription.on('loadSubset:error', ({ error, options }) => {
138 console.error('Subset failed', options, error)
139})
140
141subscription.requestSnapshot()
142
143// The most recent failure remains available for diagnostics.
144console.log(subscription.lastError)
145```
146
147For ordered live queries, `utils.setWindow()` rejects with the same error. The
148last failure is also available as `utils.lastSubsetError`, while the last
149successful snapshot remains readable:
150
151```ts
152try {
153 await liveTodos.utils.setWindow({ offset: 0, limit: 100 })
154} catch (error) {
155 console.error(liveTodos.utils.lastSubsetError)
156}
157```
158
159Effects report subset failures through `onSourceError` and dispose because
160their incremental result can no longer be kept complete.
161
162When a source change invalidates an ordered window, automatic full-source
163repair keeps the last complete snapshot visible. A failed repair exposes
164`utils.lastSubsetError` and retries at most twice, after 250 ms and 500 ms.
165Exhausting those retries does not put an already-ready query into a terminal
166error state or clear its rows. The app can show the error and explicitly retry
167with `setWindow()`. Cleanup or truncate cancels the old repair timer. Failed
168imperative window moves and initial loads do not use this background retry.
169
170For SQLite-persisted on-demand collections, a failed upstream `loadSubset`
171rejects even when hydration succeeded. Cached rows remain readable; their
172availability does not mean the remote request succeeded. Background coordinator
173retry, where supported, does not change the failed caller's outcome.
174
175When a must-refetch truncate cannot reload every active subset, a subscription
176keeps its last successful snapshot and reports the subset error. It discards
177the incomplete replay batch and keeps later source changes private because they
178cannot prove a complete replacement. The next truncate retries every active
179subset. Overlapping truncates form one atomic replay: all in-flight requests
180settle, the newest attempt decides the result, and subscribers receive the
181replacement only when that attempt succeeds. Cleanup rejects window moves that
182are waiting for replay with `AbortError`.
183
184## Collection Status and Error States
185
186Collections track their status and transition between states:
187
188```tsx
189import { useLiveQuery } from "@tanstack/react-db"
190
191const TodoList = () => {
192 const { data, status, isError, isLoading, isReady } = useLiveQuery(
193 (query) => query.from({ todos: todoCollection })
194 )
195
196 if (isError) {
197 return <div>Collection is in error state</div>
198 }
199
200 if (isLoading) {
201 return <div>Loading...</div>
202 }
203
204 return <div>{data?.map(todo => <div key={todo.id}>{todo.text}</div>)}</div>
205}
206```
207
208Collection status values:
209- `idle` - Not yet started
210- `loading` - Loading initial data
211- `initialCommit` - Processing initial data
212- `ready` - Ready for use
213- `error` - In error state
214- `cleaned-up` - Cleaned up and no longer usable
215
216### Using Suspense and Error Boundaries (React)
217
218For React applications, you can handle loading and error states with `useLiveSuspenseQuery`, React Suspense, and Error Boundaries:
219
220```tsx
221import { useLiveSuspenseQuery } from "@tanstack/react-db"
222import { Suspense } from "react"
223import { ErrorBoundary } from "react-error-boundary"
224
225const TodoList = () => {
226 // No need to check status - Suspense and ErrorBoundary handle it
227 const { data } = useLiveSuspenseQuery(
228 (query) => query.from({ todos: todoCollection })
229 )
230
231 // data is always defined here
232 return <div>{data.map(todo => <div key={todo.id}>{todo.text}</div>)}</div>
233}
234
235const App = () => (
236 <ErrorBoundary fallback={<div>Failed to load todos</div>}>
237 <Suspense fallback={<div>Loading...</div>}>
238 <TodoList />
239 </Suspense>
240 </ErrorBoundary>
241)
242```
243
244With this approach, loading states are handled by `<Suspense>` and error states are handled by `<ErrorBoundary>` instead of within your component logic. See the [React Suspense section in Live Queries](./live-queries#using-with-react-suspense) for more details.
245
246When every eager SQLite persisted source opts in, a failed client query stream can produce a different initial result. React waits for every persisted restore. If each restore succeeds, React renders the query result. A derived-query failure still reaches the Error Boundary. See [Render after SQLite restore](./sqlite-persistence.md#render-after-sqlite-restore) for the option and its limits.
247
248## Transaction Error Handling
249
250When mutations fail, TanStack DB automatically rolls back optimistic updates:
251
252```ts
253const todoCollection = createCollection({
254 id: "todos",
255 onInsert: async ({ transaction }) => {
256 const response = await fetch("/api/todos", {
257 method: "POST",
258 body: JSON.stringify(transaction.mutations[0].modified),
259 })
261 if (!response.ok) {
262 // Throwing an error will rollback the optimistic state
263 throw new Error(`HTTP Error: ${response.status}`)
264 }
266 return response.json()
267 },
268})
269
270// Usage - optimistic update will be rolled back if the mutation fails
271try {
272 const tx = todoCollection.insert({
273 id: "1",
274 text: "New todo",
275 completed: false,
276 })
278 await tx.isPersisted.promise
279} catch (error) {
280 // The optimistic update has been automatically rolled back
281 console.error("Failed to create todo:", error)
282}
283```
284
285### Transaction States and Error Information
286
287Transactions have the following states:
288- `pending` - Transaction is being processed
289- `persisting` - Currently executing the mutation function
290- `completed` - Transaction completed successfully
291- `failed` - Transaction failed and was rolled back
292
293Access transaction error information from collection operations:
294
295```ts
296const todoCollection = createCollection({
297 id: "todos",
298 onUpdate: async ({ transaction }) => {
299 const response = await fetch(`/api/todos/${transaction.mutations[0].key}`, {
300 method: "PUT",
301 body: JSON.stringify(transaction.mutations[0].modified),
302 })
304 if (!response.ok) {
305 throw new Error(`Update failed: ${response.status}`)
306 }
307 },
308})
309
310try {
311 const tx = await todoCollection.update("todo-1", (draft) => {
312 draft.completed = true
313 })
315 await tx.isPersisted.promise
316} catch (error) {
317 // Transaction has been rolled back
318 console.log(tx.state) // "failed"
319 console.log(tx.error) // { message: "Update failed: 500", error: Error }
320}
321```
322
323Or with manual transaction creation:
324
325```ts
326const tx = createTransaction({
327 mutationFn: async ({ transaction }) => {
328 throw new Error("API failed")
329 }
330})
331
332tx.mutate(() => {
333 collection.insert({ id: "1", text: "Item" })
334})
335
336try {
337 await tx.commit()
338} catch (error) {
339 // Transaction has been rolled back
340 console.log(tx.state) // "failed"
341 console.log(tx.error) // { message: "API failed", error: Error }
342}
343```
344
345Explicit cancellation is different from a mutation failure. If you call
346`tx.rollback()` while `mutationFn` is pending, the rollback settles
347`tx.isPersisted.promise` as rejected. A later result or rejection from that
348mutation function is ignored: the outstanding `commit()` call resolves and
349`tx.error` is not populated by that late rejection. Observe `isPersisted.promise`
350when you need the transaction's outcome, including explicit cancellation.
351
352After the mutation function succeeds, a publication listener can still throw
353while the completed transaction updates its collections. In that case
354`commit()` rejects with the listener error, but `isPersisted.promise` resolves
355and the transaction remains completed. This is not a persistence failure.
356
357## Collection Operation Errors
358
359### Invalid Collection State
360
361Collections in an `error` state cannot perform operations and must be manually recovered:
362
363```ts
364import { CollectionInErrorStateError } from "@tanstack/db"
365
366try {
367 todoCollection.insert(newTodo)
368} catch (error) {
369 if (error instanceof CollectionInErrorStateError) {
370 // Collection needs to be cleaned up and restarted
371 await todoCollection.cleanup()
372 await todoCollection.preload()
374 // Now retry the operation
375 todoCollection.insert(newTodo)
376 }
377}
378```
379
380If a live query depends on this Collection, restart both Collections as shown
381in [Collection Cleanup and Restart](#collection-cleanup-and-restart).
382
383### Missing Mutation Handlers
384
385Direct mutations require handlers to be configured:
386
387```ts
388const todoCollection = createCollection({
389 id: "todos",
390 getKey: (todo) => todo.id,
391 // Missing onInsert handler
392})
393
394// This will throw an error
395todoCollection.insert(newTodo)
396// Error: Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured
397```
398
399### Insert Operation Errors
400
401#### DuplicateKeyError
402
403Thrown when inserting items with existing keys:
404
405```ts
406import { DuplicateKeyError } from "@tanstack/db"
407
408try {
409 todoCollection.insert({ id: "existing-id", text: "Todo" })
410} catch (error) {
411 if (error instanceof DuplicateKeyError) {
412 console.log(`Duplicate key: ${error.message}`)
413 // Consider using update() instead, or check if item exists first
414 }
415}
416```
417
418#### UndefinedKeyError
419
420Thrown when an object is created without a defined key:
421
422```ts
423import { UndefinedKeyError } from "@tanstack/db"
424
425const collection = createCollection({
426 id: "todos",
427 getKey: (item) => item.id,
428})
429
430try {
431 collection.insert({ text: "Todo" }) // Missing 'id' field
432} catch (error) {
433 if (error instanceof UndefinedKeyError) {
434 console.log("Item is missing required key field")
435 // Ensure your items have the key field defined by getKey
436 }
437}
438```
439
440### Update Operation Errors
441
442#### UpdateKeyNotFoundError
443
444Thrown when trying to update a key that doesn't exist in the collection:
445
446```ts
447import { UpdateKeyNotFoundError } from "@tanstack/db"
448
449try {
450 todoCollection.update("nonexistent-key", draft => {
451 draft.completed = true
452 })
453} catch (error) {
454 if (error instanceof UpdateKeyNotFoundError) {
455 console.log("Key not found - item may have been deleted")
456 // Consider using insert() if the item doesn't exist
457 }
458}
459```
460
461#### KeyUpdateNotAllowedError
462
463Thrown when attempting to change an item's key (not allowed - delete and re-insert instead):
464
465```ts
466import { KeyUpdateNotAllowedError } from "@tanstack/db"
467
468try {
469 todoCollection.update("todo-1", draft => {
470 draft.id = "todo-2" // Not allowed!
471 })
472} catch (error) {
473 if (error instanceof KeyUpdateNotAllowedError) {
474 console.log("Cannot change item keys")
475 // Instead, delete the old item and insert a new one
476 }
477}
478```
479
480### Delete Operation Errors
481
482#### DeleteKeyNotFoundError
483
484Thrown when trying to delete a key that doesn't exist:
485
486```ts
487import { DeleteKeyNotFoundError } from "@tanstack/db"
488
489try {
490 todoCollection.delete("nonexistent-key")
491} catch (error) {
492 if (error instanceof DeleteKeyNotFoundError) {
493 console.log("Key not found - item may have already been deleted")
494 // This may be acceptable in some scenarios (idempotent deletes)
495 }
496}
497```
498
499## Sync Error Handling
500
501### Query Collection Sync Errors
502
503Query collections distinguish an initial load failure from a later refetch failure:
504
505```ts
506import { queryCollectionOptions } from "@tanstack/query-db-collection"
507
508const todoCollection = createCollection(
509 queryCollectionOptions({
510 queryKey: ["todos"],
511 queryFn: async () => {
512 const response = await fetch("/api/todos")
513 if (!response.ok) {
514 throw new Error(`Failed to fetch: ${response.status}`)
515 }
516 return response.json()
517 },
518 queryClient,
519 getKey: (item) => item.id,
520 schema: todoSchema,
521 // Standard TanStack Query error handling options
522 retry: 3,
523 retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
524 })
525)
526```
527
528When sync errors occur:
529- Error is logged to console: `[QueryCollection] Error observing query...`
530- An initial failure marks the collection as `error` because no usable snapshot exists
531- Readiness waits such as `preload()` and `toArrayWhenReady()` reject with the cause passed to `markError(error)` while the collection is in that initial error state
532- A later refetch failure keeps the collection `ready` and preserves its cached data
533- Error tracking counters are updated (`lastError`, `errorCount`)
534- A later successful refetch recovers an initial `error` collection to `ready`; a new readiness wait then resolves normally
535
536### Sync Write Errors
537
538Sync functions must handle their own errors during write operations:
539
540```ts
541const collection = createCollection({
542 id: "todos",
543 sync: {
544 sync: ({ begin, write, commit }) => {
545 begin()
547 try {
548 // Will throw if key already exists
549 write({ type: "insert", value: { id: "existing-id", text: "Todo" } })
550 } catch (error) {
551 // Error: Cannot insert document with key "existing-id" from sync because it already exists
552 }
554 commit()
555 }
556 }
557})
558```
559
560### Cleanup Error Handling
561
562Cleanup errors are isolated to prevent blocking the cleanup process:
563
564```ts
565const collection = createCollection({
566 id: "todos",
567 sync: {
568 sync: ({ begin, commit }) => {
569 begin()
570 commit()
572 // Return a cleanup function
573 return () => {
574 // If this throws, the error is re-thrown in a microtask
575 // but cleanup continues successfully
576 throw new Error("Sync cleanup failed")
577 }
578 },
579 },
580})
581
582// Cleanup completes even if the sync cleanup function throws
583await collection.cleanup() // Resolves successfully
584// Error is re-thrown asynchronously via queueMicrotask
585```
586
587## Error Recovery Patterns
588
589### Collection Cleanup and Restart
590
591Cleanup ends the current sync run and releases the resources installed by its
592`sync()` call. A later access can start a new sync run. If no live query or
593Effect depends on the source Collection, restart it like this:
594
595```ts
596if (todoCollection.status === "error") {
597 // Cleanup ends the current sync run and resets the collection
598 await todoCollection.cleanup()
600 // Start a new sync run and wait for readiness
601 await todoCollection.preload()
602}
603```
604
605Cleaning up a source Collection while a live-query Collection depends on it
606puts that live query in a terminal error state. Restarting the source alone
607does not revive the live query. If you own both Collections, clean up the
608dependent live query first. Preloading it after source cleanup starts fresh
609sync runs for both Collections and waits for the query's required data:
610
611```ts
612const todosQuery = createLiveQueryCollection((q) =>
613 q.from({ todos: todoCollection }),
614)
615await todosQuery.preload()
616
617// Later, if todoCollection enters an error state:
618await todosQuery.cleanup()
619await todoCollection.cleanup()
620await todosQuery.preload()
621```
622
623The same `todosQuery` object and its subscribers can receive later source
624updates after this sequence. A framework hook that creates its own live-query
625Collection may retain it across renders or remounts. Use a pre-created
626live-query Collection when you need to control this cleanup and restart
627sequence. A successful preload establishes Collection readiness; whether the
628source has caught up with a remote service depends on its sync adapter.
629Cleanup also disposes dependent Effects; recreate them after the source restarts.
630
631### Graceful Degradation
632
633Collections continue to work with cached data even when sync fails:
634
635```tsx
636const TodoApp = () => {
637 const { data, isError } = useLiveQuery((query) =>
638 query.from({ todos: todoCollection })
639 )
640
641 return (
642 <div>
643 {isError && (
644 <div>Sync failed, but you can still view cached data</div>
645 )}
646 {data?.map(todo => <TodoItem key={todo.id} todo={todo} />)}
647 </div>
648 )
649}
650```
651
652### Transaction Rollback Cascading
653
654When a transaction fails, conflicting transactions are automatically rolled back:
655
656```ts
657const tx1 = createTransaction({ mutationFn: async () => {} })
658const tx2 = createTransaction({ mutationFn: async () => {} })
659
660tx1.mutate(() => collection.update("1", draft => { draft.value = "A" }))
661tx2.mutate(() => collection.update("1", draft => { draft.value = "B" })) // Same item
662
663// Rolling back tx1 will also rollback tx2 due to conflict
664tx1.rollback() // tx2 is automatically rolled back
665```
666
667### Transaction Lifecycle Errors
668
669Transactions validate their state before operations to prevent misuse. Here are the specific errors you may encounter:
670
671#### MissingMutationFunctionError
672
673Thrown when creating a transaction without a required `mutationFn`:
674
675```ts
676import { MissingMutationFunctionError } from "@tanstack/db"
677
678try {
679 const tx = createTransaction({}) // Missing mutationFn
680} catch (error) {
681 if (error instanceof MissingMutationFunctionError) {
682 console.log("mutationFn is required when creating a transaction")
683 }
684}
685```
686
687#### TransactionNotPendingMutateError
688
689Thrown when calling `mutate()` after a transaction is no longer pending:
690
691```ts
692import { TransactionNotPendingMutateError } from "@tanstack/db"
693
694const tx = createTransaction({ mutationFn: async () => {} })
695
696await tx.commit()
697
698try {
699 tx.mutate(() => {
700 collection.insert({ id: "1", text: "Item" })
701 })
702} catch (error) {
703 if (error instanceof TransactionNotPendingMutateError) {
704 console.log("Cannot mutate - transaction is no longer pending")
705 }
706}
707```
708
709#### TransactionNotPendingCommitError
710
711Thrown when calling `commit()` after a transaction is no longer pending:
712
713```ts
714import { TransactionNotPendingCommitError } from "@tanstack/db"
715
716const tx = createTransaction({ mutationFn: async () => {} })
717tx.mutate(() => collection.insert({ id: "1", text: "Item" }))
718
719await tx.commit()
720
721try {
722 await tx.commit() // Trying to commit again
723} catch (error) {
724 if (error instanceof TransactionNotPendingCommitError) {
725 console.log("Transaction already committed")
726 }
727}
728```
729
730#### TransactionAlreadyCompletedRollbackError
731
732Thrown when calling `rollback()` on a transaction that's already completed:
733
734```ts
735import { TransactionAlreadyCompletedRollbackError } from "@tanstack/db"
736
737const tx = createTransaction({ mutationFn: async () => {} })
738tx.mutate(() => collection.insert({ id: "1", text: "Item" }))
739
740await tx.commit()
741
742try {
743 tx.rollback() // Can't rollback after commit
744} catch (error) {
745 if (error instanceof TransactionAlreadyCompletedRollbackError) {
746 console.log("Cannot rollback - transaction already completed")
747 }
748}
749```
750
751### Sync Transaction Errors
752
753When working with sync transactions, these errors can occur:
754
755#### NoPendingSyncTransactionWriteError
756
757Thrown when calling `write()` without an active sync transaction:
758
759```ts
760const collection = createCollection({
761 id: "todos",
762 sync: {
763 sync: ({ write }) => {
764 // Calling write without begin() first
765 write({ type: "insert", value: { id: "1", text: "Todo" } })
766 // Error: No pending sync transaction to write to
767 }
768 }
769})
770```
771
772#### SyncTransactionAlreadyCommittedWriteError
773
774Thrown when calling `write()` after the sync transaction is already committed:
775
776```ts
777const collection = createCollection({
778 id: "todos",
779 sync: {
780 sync: ({ begin, write, commit }) => {
781 begin()
782 commit()
783
784 // Trying to write after commit
785 write({ type: "insert", value: { id: "1", text: "Todo" } })
786 // Error: The pending sync transaction is already committed
787 }
788 }
789})
790```
791
792#### NoPendingSyncTransactionCommitError
793
794Thrown when calling `commit()` without an active sync transaction.
795
796#### SyncTransactionAlreadyCommittedError
797
798Thrown when calling `commit()` on a sync transaction that's already committed.
799
800## Best Practices
801
8021. **Use instanceof checks** - Use `instanceof` instead of string matching for error handling:
803 ```ts
804 // ✅ Good - type-safe error handling
805 if (error instanceof SchemaValidationError) {
806 // Handle validation error
807 }
809 // ❌ Avoid - brittle string matching
810 if (error.message.includes("validation failed")) {
811 // Handle validation error
812 }
813 ```
814
8152. **Import specific error types** - Import only the error classes you need for better tree-shaking
8163. **Always handle SchemaValidationError** - Provide clear feedback for validation failures
8174. **Check collection status** - Use `isError`, `isLoading`, `isReady` flags in React components
8185. **Handle transaction promises** - Always handle `isPersisted.promise` rejections
819
820## Example: Complete Error Handling
821
822```tsx
823import {
824 createCollection,
825 createLiveQueryCollection,
826 SchemaValidationError,
827 DuplicateKeyError,
828 UpdateKeyNotFoundError,
829 DeleteKeyNotFoundError,
830 TransactionNotPendingCommitError,
831 createTransaction
832} from "@tanstack/db"
833import { useLiveQuery } from "@tanstack/react-db"
834
835const todoCollection = createCollection({
836 id: "todos",
837 schema: todoSchema,
838 getKey: (todo) => todo.id,
839 onInsert: async ({ transaction }) => {
840 const response = await fetch("/api/todos", {
841 method: "POST",
842 body: JSON.stringify(transaction.mutations[0].modified),
843 })
844
845 if (!response.ok) {
846 throw new Error(`HTTP ${response.status}: ${response.statusText}`)
847 }
848
849 return response.json()
850 },
851 sync: {
852 sync: ({ begin, write, commit, markReady }) => {
853 // Your sync implementation
854 begin()
855 // ... sync logic
856 commit()
857 markReady()
858 }
859 }
860})
861
862const todosQuery = createLiveQueryCollection((query) =>
863 query.from({ todos: todoCollection })
864)
865
866const TodoApp = () => {
867 const { data, isError, isLoading } = useLiveQuery(todosQuery)
868
869 const handleAddTodo = async (text: string) => {
870 try {
871 const tx = await todoCollection.insert({
872 id: crypto.randomUUID(),
873 text,
874 completed: false,
875 })
877 // Wait for persistence
878 await tx.isPersisted.promise
879 } catch (error) {
880 if (error instanceof SchemaValidationError) {
881 alert(`Validation error: ${error.issues[0]?.message}`)
882 } else if (error instanceof DuplicateKeyError) {
883 alert("A todo with this ID already exists")
884 } else {
885 alert(`Failed to add todo: ${error.message}`)
886 }
887 }
888 }
889
890 const handleRestart = async () => {
891 try {
892 await todosQuery.cleanup()
893 await todoCollection.cleanup()
894 await todosQuery.preload()
895 } catch (error) {
896 alert(`Failed to restart todos: ${String(error)}`)
897 }
898 }
899
900 if (isError) {
901 return (
902 <div>
903 <div>Collection error - data may be stale</div>
904 <button onClick={handleRestart}>Restart Collections</button>
905 </div>
906 )
907 }
908
909 if (isLoading) {
910 return <div>Loading todos...</div>
911 }
912
913 return (
914 <div>
915 <button onClick={() => handleAddTodo("New todo")}>
916 Add Todo
917 </button>
918 {data?.map(todo => (
919 <div key={todo.id}>{todo.text}</div>
920 ))}
921 </div>
922 )
923}
924```
925
926## See Also
927
928- [API Reference](../overview.md#api-reference) - Detailed API documentation
929- [Mutations Guide](../overview.md#making-optimistic-mutations) - Learn about optimistic updates and rollbacks
930- [TanStack Query Error Handling](https://tanstack.com/query/latest/docs/react/guides/error-handling) - Query-specific error handling