Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

error-handling.md

889 lines24.7 KB

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 }
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 })
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 )
112```
113​
114Error tracking methods:
115- **`lastError`**: Returns the most recent error encountered by the query, or `undefined` if no errors have occurred:
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 on successful queries:
118- **`clearError()`**: Clears the error state and triggers a refetch of the query. This method resets both `lastError` and `errorCount`:
119​
120## Incremental Subset Load Errors
121​
122An incremental `loadSubset` failure does not discard rows that are already
123available or put the shared source collection into `error`. The failure belongs
124to the subscription that requested that subset:
125​
126```ts
127const subscription = todoCollection.subscribeChanges(handleChanges, {
128 includeInitialState: false,
129})
130​
131subscription.on('loadSubset:error', ({ error, options }) => {
132 console.error('Subset failed', options, error)
133})
134​
135subscription.requestSnapshot()
136​
137// The most recent failure remains available for diagnostics.
138console.log(subscription.lastError)
139```
140​
141For ordered live queries, `utils.setWindow()` rejects with the same error. The
142last failure is also available as `utils.lastSubsetError`, while the last
143successful snapshot remains readable:
144​
145```ts
146try {
147 await liveTodos.utils.setWindow({ offset: 0, limit: 100 })
148} catch (error) {
149 console.error(liveTodos.utils.lastSubsetError)
151```
152​
153Effects report subset failures through `onSourceError` and dispose because
154their incremental result can no longer be kept complete.
155​
156When a source change invalidates an ordered window, automatic full-source
157repair keeps the last complete snapshot visible. A failed repair exposes
158`utils.lastSubsetError` and retries at most twice, after 250 ms and 500 ms.
159Exhausting those retries does not put an already-ready query into a terminal
160error state or clear its rows. The app can show the error and explicitly retry
161with `setWindow()`. Cleanup or truncate cancels the old repair timer. Failed
162imperative window moves and initial loads do not use this background retry.
163​
164For SQLite-persisted on-demand collections, a failed upstream `loadSubset`
165rejects even when hydration succeeded. Cached rows remain readable; their
166availability does not mean the remote request succeeded. Background coordinator
167retry, where supported, does not change the failed caller's outcome.
168​
169When a must-refetch truncate cannot reload every active subset, a subscription
170keeps its last successful snapshot and reports the subset error. It discards
171the incomplete replay batch and keeps later source changes private because they
172cannot prove a complete replacement. The next truncate retries every active
173subset. Overlapping truncates form one atomic replay: all in-flight requests
174settle, the newest attempt decides the result, and subscribers receive the
175replacement only when that attempt succeeds. Cleanup rejects window moves that
176are waiting for replay with `AbortError`.
177​
178## Collection Status and Error States
179​
180Collections track their status and transition between states:
181​
182```tsx
183import { useLiveQuery } from "@tanstack/react-db"
184​
185const TodoList = () => {
186 const { data, status, isError, isLoading, isReady } = useLiveQuery(
187 (query) => query.from({ todos: todoCollection })
188 )
189​
190 if (isError) {
191 return <div>Collection is in error state</div>
192 }
193​
194 if (isLoading) {
195 return <div>Loading...</div>
196 }
197​
198 return <div>{data?.map(todo => <div key={todo.id}>{todo.text}</div>)}</div>
200```
201​
202Collection status values:
203- `idle` - Not yet started
204- `loading` - Loading initial data
205- `initialCommit` - Processing initial data
206- `ready` - Ready for use
207- `error` - In error state
208- `cleaned-up` - Cleaned up and no longer usable
209​
210### Using Suspense and Error Boundaries (React)
211​
212For React applications, you can handle loading and error states with `useLiveSuspenseQuery`, React Suspense, and Error Boundaries:
213​
214```tsx
215import { useLiveSuspenseQuery } from "@tanstack/react-db"
216import { Suspense } from "react"
217import { ErrorBoundary } from "react-error-boundary"
218​
219const TodoList = () => {
220 // No need to check status - Suspense and ErrorBoundary handle it
221 const { data } = useLiveSuspenseQuery(
222 (query) => query.from({ todos: todoCollection })
223 )
224​
225 // data is always defined here
226 return <div>{data.map(todo => <div key={todo.id}>{todo.text}</div>)}</div>
228​
229const App = () => (
230 <ErrorBoundary fallback={<div>Failed to load todos</div>}>
231 <Suspense fallback={<div>Loading...</div>}>
232 <TodoList />
233 </Suspense>
234 </ErrorBoundary>
236```
237​
238With 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.
239​
240## Transaction Error Handling
241​
242When mutations fail, TanStack DB automatically rolls back optimistic updates:
243​
244```ts
245const todoCollection = createCollection({
246 id: "todos",
247 onInsert: async ({ transaction }) => {
248 const response = await fetch("/api/todos", {
249 method: "POST",
250 body: JSON.stringify(transaction.mutations[0].modified),
251 })
253 if (!response.ok) {
254 // Throwing an error will rollback the optimistic state
255 throw new Error(`HTTP Error: ${response.status}`)
256 }
258 return response.json()
259 },
260})
261​
262// Usage - optimistic update will be rolled back if the mutation fails
263try {
264 const tx = todoCollection.insert({
265 id: "1",
266 text: "New todo",
267 completed: false,
268 })
270 await tx.isPersisted.promise
271} catch (error) {
272 // The optimistic update has been automatically rolled back
273 console.error("Failed to create todo:", error)
275```
276​
277### Transaction States and Error Information
278​
279Transactions have the following states:
280- `pending` - Transaction is being processed
281- `persisting` - Currently executing the mutation function
282- `completed` - Transaction completed successfully
283- `failed` - Transaction failed and was rolled back
284​
285Access transaction error information from collection operations:
286​
287```ts
288const todoCollection = createCollection({
289 id: "todos",
290 onUpdate: async ({ transaction }) => {
291 const response = await fetch(`/api/todos/${transaction.mutations[0].key}`, {
292 method: "PUT",
293 body: JSON.stringify(transaction.mutations[0].modified),
294 })
296 if (!response.ok) {
297 throw new Error(`Update failed: ${response.status}`)
298 }
299 },
300})
301​
302try {
303 const tx = await todoCollection.update("todo-1", (draft) => {
304 draft.completed = true
305 })
307 await tx.isPersisted.promise
308} catch (error) {
309 // Transaction has been rolled back
310 console.log(tx.state) // "failed"
311 console.log(tx.error) // { message: "Update failed: 500", error: Error }
313```
314​
315Or with manual transaction creation:
316​
317```ts
318const tx = createTransaction({
319 mutationFn: async ({ transaction }) => {
320 throw new Error("API failed")
321 }
322})
323​
324tx.mutate(() => {
325 collection.insert({ id: "1", text: "Item" })
326})
327​
328try {
329 await tx.commit()
330} catch (error) {
331 // Transaction has been rolled back
332 console.log(tx.state) // "failed"
333 console.log(tx.error) // { message: "API failed", error: Error }
335```
336​
337Explicit cancellation is different from a mutation failure. If you call
338`tx.rollback()` while `mutationFn` is pending, the rollback settles
339`tx.isPersisted.promise` as rejected. A later result or rejection from that
340mutation function is ignored: the outstanding `commit()` call resolves and
341`tx.error` is not populated by that late rejection. Observe `isPersisted.promise`
342when you need the transaction's outcome, including explicit cancellation.
343​
344After the mutation function succeeds, a publication listener can still throw
345while the completed transaction updates its collections. In that case
346`commit()` rejects with the listener error, but `isPersisted.promise` resolves
347and the transaction remains completed. This is not a persistence failure.
348​
349## Collection Operation Errors
350​
351### Invalid Collection State
352​
353Collections in an `error` state cannot perform operations and must be manually recovered:
354​
355```ts
356import { CollectionInErrorStateError } from "@tanstack/db"
357​
358try {
359 todoCollection.insert(newTodo)
360} catch (error) {
361 if (error instanceof CollectionInErrorStateError) {
362 // Collection needs to be cleaned up and restarted
363 await todoCollection.cleanup()
365 // Now retry the operation
366 todoCollection.insert(newTodo)
367 }
369```
370​
371### Missing Mutation Handlers
372​
373Direct mutations require handlers to be configured:
374​
375```ts
376const todoCollection = createCollection({
377 id: "todos",
378 getKey: (todo) => todo.id,
379 // Missing onInsert handler
380})
381​
382// This will throw an error
383todoCollection.insert(newTodo)
384// Error: Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured
385```
386​
387### Insert Operation Errors
388​
389#### DuplicateKeyError
390​
391Thrown when inserting items with existing keys:
392​
393```ts
394import { DuplicateKeyError } from "@tanstack/db"
395​
396try {
397 todoCollection.insert({ id: "existing-id", text: "Todo" })
398} catch (error) {
399 if (error instanceof DuplicateKeyError) {
400 console.log(`Duplicate key: ${error.message}`)
401 // Consider using update() instead, or check if item exists first
402 }
404```
405​
406#### UndefinedKeyError
407​
408Thrown when an object is created without a defined key:
409​
410```ts
411import { UndefinedKeyError } from "@tanstack/db"
412​
413const collection = createCollection({
414 id: "todos",
415 getKey: (item) => item.id,
416})
417​
418try {
419 collection.insert({ text: "Todo" }) // Missing 'id' field
420} catch (error) {
421 if (error instanceof UndefinedKeyError) {
422 console.log("Item is missing required key field")
423 // Ensure your items have the key field defined by getKey
424 }
426```
427​
428### Update Operation Errors
429​
430#### UpdateKeyNotFoundError
431​
432Thrown when trying to update a key that doesn't exist in the collection:
433​
434```ts
435import { UpdateKeyNotFoundError } from "@tanstack/db"
436​
437try {
438 todoCollection.update("nonexistent-key", draft => {
439 draft.completed = true
440 })
441} catch (error) {
442 if (error instanceof UpdateKeyNotFoundError) {
443 console.log("Key not found - item may have been deleted")
444 // Consider using insert() if the item doesn't exist
445 }
447```
448​
449#### KeyUpdateNotAllowedError
450​
451Thrown when attempting to change an item's key (not allowed - delete and re-insert instead):
452​
453```ts
454import { KeyUpdateNotAllowedError } from "@tanstack/db"
455​
456try {
457 todoCollection.update("todo-1", draft => {
458 draft.id = "todo-2" // Not allowed!
459 })
460} catch (error) {
461 if (error instanceof KeyUpdateNotAllowedError) {
462 console.log("Cannot change item keys")
463 // Instead, delete the old item and insert a new one
464 }
466```
467​
468### Delete Operation Errors
469​
470#### DeleteKeyNotFoundError
471​
472Thrown when trying to delete a key that doesn't exist:
473​
474```ts
475import { DeleteKeyNotFoundError } from "@tanstack/db"
476​
477try {
478 todoCollection.delete("nonexistent-key")
479} catch (error) {
480 if (error instanceof DeleteKeyNotFoundError) {
481 console.log("Key not found - item may have already been deleted")
482 // This may be acceptable in some scenarios (idempotent deletes)
483 }
485```
486​
487## Sync Error Handling
488​
489### Query Collection Sync Errors
490​
491Query collections distinguish an initial load failure from a later refetch failure:
492​
493```ts
494import { queryCollectionOptions } from "@tanstack/query-db-collection"
495​
496const todoCollection = createCollection(
497 queryCollectionOptions({
498 queryKey: ["todos"],
499 queryFn: async () => {
500 const response = await fetch("/api/todos")
501 if (!response.ok) {
502 throw new Error(`Failed to fetch: ${response.status}`)
503 }
504 return response.json()
505 },
506 queryClient,
507 getKey: (item) => item.id,
508 schema: todoSchema,
509 // Standard TanStack Query error handling options
510 retry: 3,
511 retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
512 })
514```
515​
516When sync errors occur:
517- Error is logged to console: `[QueryCollection] Error observing query...`
518- An initial failure marks the collection as `error` because no usable snapshot exists
519- Readiness waits such as `preload()` and `toArrayWhenReady()` reject with the cause passed to `markError(error)` while the collection is in that initial error state
520- A later refetch failure keeps the collection `ready` and preserves its cached data
521- Error tracking counters are updated (`lastError`, `errorCount`)
522- A later successful refetch recovers an initial `error` collection to `ready`; a new readiness wait then resolves normally
523​
524### Sync Write Errors
525​
526Sync functions must handle their own errors during write operations:
527​
528```ts
529const collection = createCollection({
530 id: "todos",
531 sync: {
532 sync: ({ begin, write, commit }) => {
533 begin()
535 try {
536 // Will throw if key already exists
537 write({ type: "insert", value: { id: "existing-id", text: "Todo" } })
538 } catch (error) {
539 // Error: Cannot insert document with key "existing-id" from sync because it already exists
540 }
542 commit()
543 }
544 }
545})
546```
547​
548### Cleanup Error Handling
549​
550Cleanup errors are isolated to prevent blocking the cleanup process:
551​
552```ts
553const collection = createCollection({
554 id: "todos",
555 sync: {
556 sync: ({ begin, commit }) => {
557 begin()
558 commit()
560 // Return a cleanup function
561 return () => {
562 // If this throws, the error is re-thrown in a microtask
563 // but cleanup continues successfully
564 throw new Error("Sync cleanup failed")
565 }
566 },
567 },
568})
569​
570// Cleanup completes even if the sync cleanup function throws
571await collection.cleanup() // Resolves successfully
572// Error is re-thrown asynchronously via queueMicrotask
573```
574​
575## Error Recovery Patterns
576​
577### Collection Cleanup and Restart
578​
579Cleanup ends the current sync run and releases the resources installed by its
580`sync()` call. A later access can start a new sync run. Clean up collections in
581error states like this:
582​
583```ts
584if (todoCollection.status === "error") {
585 // Cleanup ends the current sync run and resets the collection
586 await todoCollection.cleanup()
588 // The next access starts a new sync run
589 todoCollection.preload() // Or any other operation
591```
592​
593### Graceful Degradation
594​
595Collections continue to work with cached data even when sync fails:
596​
597```tsx
598const TodoApp = () => {
599 const { data, isError } = useLiveQuery((query) =>
600 query.from({ todos: todoCollection })
601 )
602​
603 return (
604 <div>
605 {isError && (
606 <div>Sync failed, but you can still view cached data</div>
607 )}
608 {data?.map(todo => <TodoItem key={todo.id} todo={todo} />)}
609 </div>
610 )
612```
613​
614### Transaction Rollback Cascading
615​
616When a transaction fails, conflicting transactions are automatically rolled back:
617​
618```ts
619const tx1 = createTransaction({ mutationFn: async () => {} })
620const tx2 = createTransaction({ mutationFn: async () => {} })
621​
622tx1.mutate(() => collection.update("1", draft => { draft.value = "A" }))
623tx2.mutate(() => collection.update("1", draft => { draft.value = "B" })) // Same item
624​
625// Rolling back tx1 will also rollback tx2 due to conflict
626tx1.rollback() // tx2 is automatically rolled back
627```
628​
629### Transaction Lifecycle Errors
630​
631Transactions validate their state before operations to prevent misuse. Here are the specific errors you may encounter:
632​
633#### MissingMutationFunctionError
634​
635Thrown when creating a transaction without a required `mutationFn`:
636​
637```ts
638import { MissingMutationFunctionError } from "@tanstack/db"
639​
640try {
641 const tx = createTransaction({}) // Missing mutationFn
642} catch (error) {
643 if (error instanceof MissingMutationFunctionError) {
644 console.log("mutationFn is required when creating a transaction")
645 }
647```
648​
649#### TransactionNotPendingMutateError
650​
651Thrown when calling `mutate()` after a transaction is no longer pending:
652​
653```ts
654import { TransactionNotPendingMutateError } from "@tanstack/db"
655​
656const tx = createTransaction({ mutationFn: async () => {} })
657​
658await tx.commit()
659​
660try {
661 tx.mutate(() => {
662 collection.insert({ id: "1", text: "Item" })
663 })
664} catch (error) {
665 if (error instanceof TransactionNotPendingMutateError) {
666 console.log("Cannot mutate - transaction is no longer pending")
667 }
669```
670​
671#### TransactionNotPendingCommitError
672​
673Thrown when calling `commit()` after a transaction is no longer pending:
674​
675```ts
676import { TransactionNotPendingCommitError } from "@tanstack/db"
677​
678const tx = createTransaction({ mutationFn: async () => {} })
679tx.mutate(() => collection.insert({ id: "1", text: "Item" }))
680​
681await tx.commit()
682​
683try {
684 await tx.commit() // Trying to commit again
685} catch (error) {
686 if (error instanceof TransactionNotPendingCommitError) {
687 console.log("Transaction already committed")
688 }
690```
691​
692#### TransactionAlreadyCompletedRollbackError
693​
694Thrown when calling `rollback()` on a transaction that's already completed:
695​
696```ts
697import { TransactionAlreadyCompletedRollbackError } from "@tanstack/db"
698​
699const tx = createTransaction({ mutationFn: async () => {} })
700tx.mutate(() => collection.insert({ id: "1", text: "Item" }))
701​
702await tx.commit()
703​
704try {
705 tx.rollback() // Can't rollback after commit
706} catch (error) {
707 if (error instanceof TransactionAlreadyCompletedRollbackError) {
708 console.log("Cannot rollback - transaction already completed")
709 }
711```
712​
713### Sync Transaction Errors
714​
715When working with sync transactions, these errors can occur:
716​
717#### NoPendingSyncTransactionWriteError
718​
719Thrown when calling `write()` without an active sync transaction:
720​
721```ts
722const collection = createCollection({
723 id: "todos",
724 sync: {
725 sync: ({ write }) => {
726 // Calling write without begin() first
727 write({ type: "insert", value: { id: "1", text: "Todo" } })
728 // Error: No pending sync transaction to write to
729 }
730 }
731})
732```
733​
734#### SyncTransactionAlreadyCommittedWriteError
735​
736Thrown when calling `write()` after the sync transaction is already committed:
737​
738```ts
739const collection = createCollection({
740 id: "todos",
741 sync: {
742 sync: ({ begin, write, commit }) => {
743 begin()
744 commit()
745​
746 // Trying to write after commit
747 write({ type: "insert", value: { id: "1", text: "Todo" } })
748 // Error: The pending sync transaction is already committed
749 }
750 }
751})
752```
753​
754#### NoPendingSyncTransactionCommitError
755​
756Thrown when calling `commit()` without an active sync transaction.
757​
758#### SyncTransactionAlreadyCommittedError
759​
760Thrown when calling `commit()` on a sync transaction that's already committed.
761​
762## Best Practices
763​
7641. **Use instanceof checks** - Use `instanceof` instead of string matching for error handling:
765 ```ts
766 // ✅ Good - type-safe error handling
767 if (error instanceof SchemaValidationError) {
768 // Handle validation error
769 }
771 // ❌ Avoid - brittle string matching
772 if (error.message.includes("validation failed")) {
773 // Handle validation error
774 }
775 ```
776​
7772. **Import specific error types** - Import only the error classes you need for better tree-shaking
7783. **Always handle SchemaValidationError** - Provide clear feedback for validation failures
7794. **Check collection status** - Use `isError`, `isLoading`, `isReady` flags in React components
7805. **Handle transaction promises** - Always handle `isPersisted.promise` rejections
781​
782## Example: Complete Error Handling
783​
784```tsx
785import {
786 createCollection,
787 SchemaValidationError,
788 DuplicateKeyError,
789 UpdateKeyNotFoundError,
790 DeleteKeyNotFoundError,
791 TransactionNotPendingCommitError,
792 createTransaction
793} from "@tanstack/db"
794import { useLiveQuery } from "@tanstack/react-db"
795​
796const todoCollection = createCollection({
797 id: "todos",
798 schema: todoSchema,
799 getKey: (todo) => todo.id,
800 onInsert: async ({ transaction }) => {
801 const response = await fetch("/api/todos", {
802 method: "POST",
803 body: JSON.stringify(transaction.mutations[0].modified),
804 })
805​
806 if (!response.ok) {
807 throw new Error(`HTTP ${response.status}: ${response.statusText}`)
808 }
809​
810 return response.json()
811 },
812 sync: {
813 sync: ({ begin, write, commit }) => {
814 // Your sync implementation
815 begin()
816 // ... sync logic
817 commit()
818 }
819 }
820})
821​
822const TodoApp = () => {
823 const { data, status, isError, isLoading } = useLiveQuery(
824 (query) => query.from({ todos: todoCollection })
825 )
826​
827 const handleAddTodo = async (text: string) => {
828 try {
829 const tx = await todoCollection.insert({
830 id: crypto.randomUUID(),
831 text,
832 completed: false,
833 })
835 // Wait for persistence
836 await tx.isPersisted.promise
837 } catch (error) {
838 if (error instanceof SchemaValidationError) {
839 alert(`Validation error: ${error.issues[0]?.message}`)
840 } else if (error instanceof DuplicateKeyError) {
841 alert("A todo with this ID already exists")
842 } else {
843 alert(`Failed to add todo: ${error.message}`)
844 }
845 }
846 }
847​
848 const handleCleanup = async () => {
849 try {
850 await todoCollection.cleanup()
851 // Collection will restart on next access
852 } catch (error) {
853 console.error("Cleanup failed:", error)
854 }
855 }
856​
857 if (isError) {
858 return (
859 <div>
860 <div>Collection error - data may be stale</div>
861 <button onClick={handleCleanup}>
862 Restart Collection
863 </button>
864 </div>
865 )
866 }
867​
868 if (isLoading) {
869 return <div>Loading todos...</div>
870 }
871​
872 return (
873 <div>
874 <button onClick={() => handleAddTodo("New todo")}>
875 Add Todo
876 </button>
877 {data?.map(todo => (
878 <div key={todo.id}>{todo.text}</div>
879 ))}
880 </div>
881 )
883```
884​
885## See Also
886​
887- [API Reference](../overview.md#api-reference) - Detailed API documentation
888- [Mutations Guide](../overview.md#making-optimistic-mutations) - Learn about optimistic updates and rollbacks
889- [TanStack Query Error Handling](https://tanstack.com/query/latest/docs/react/guides/error-handling) - Query-specific error handling