Open History to see the last commit
1---
2title: Mutations
3id: mutations
4---
5
6# TanStack DB Mutations
7
8TanStack DB provides a powerful mutation system that enables optimistic updates with automatic state management. This system is built around a pattern of **optimistic mutation → backend persistence → sync back → confirmed state**. This creates a highly responsive user experience while maintaining data consistency and being easy to reason about.
9
10Local changes are applied immediately as optimistic state, then persisted to your backend, and finally the optimistic state is replaced by the confirmed server state once it syncs back.
11
12```tsx
13// Define a collection with a mutation handler
14const todoCollection = createCollection({
15 id: "todos",
16 onUpdate: async ({ transaction }) => {
17 const mutation = transaction.mutations[0]
18 await api.todos.update(mutation.original.id, mutation.changes)
19 },
20})
21
22// Apply an optimistic update
23todoCollection.update(todo.id, (draft) => {
24 draft.completed = true
25})
26```
27
28This pattern extends the Redux/Flux unidirectional data flow beyond the client to include the server:
29
30<figure>
31 <a href="https://raw.githubusercontent.com/TanStack/db/main/docs/unidirectional-data-flow.lg.png" target="_blank">
32 <img src="https://raw.githubusercontent.com/TanStack/db/main/docs/unidirectional-data-flow.png" />
33 </a>
34</figure>
35
36With an instant inner loop of optimistic state, superseded in time by the slower outer loop of persisting to the server and syncing the updated server state back into the collection.
37
38### Simplified Mutations vs Traditional Approaches
39
40TanStack DB's mutation system eliminates much of the boilerplate required for optimistic updates in traditional approaches. Compare the difference:
41
42**Before (TanStack Query with manual optimistic updates):**
43
44```typescript
45const addTodoMutation = useMutation({
46 mutationFn: async (newTodo) => api.todos.create(newTodo),
47 onMutate: async (newTodo) => {
48 await queryClient.cancelQueries({ queryKey: ['todos'] })
49 const previousTodos = queryClient.getQueryData(['todos'])
50 queryClient.setQueryData(['todos'], (old) => [...(old || []), newTodo])
51 return { previousTodos }
52 },
53 onError: (err, newTodo, context) => {
54 queryClient.setQueryData(['todos'], context.previousTodos)
55 },
56 onSettled: () => {
57 queryClient.invalidateQueries({ queryKey: ['todos'] })
58 },
59})
60```
61
62**After (TanStack DB):**
63
64```typescript
65const todoCollection = createCollection(
66 queryCollectionOptions({
67 queryKey: ['todos'],
68 queryFn: async () => api.todos.getAll(),
69 getKey: (item) => item.id,
70 schema: todoSchema,
71 onInsert: async ({ transaction }) => {
72 await Promise.all(
73 transaction.mutations.map((mutation) =>
74 api.todos.create(mutation.modified)
75 )
76 )
77 },
78 })
79)
80
81// Simple mutation - no boilerplate!
82todoCollection.insert({
83 id: crypto.randomUUID(),
84 text: '🔥 Make app faster',
85 completed: false,
86})
87```
88
89The benefits:
90- ✅ Automatic optimistic updates
91- ✅ Automatic rollback on error
92- ✅ No manual cache manipulation
93- ✅ Type-safe mutations
94
95## Table of Contents
96
97- [Mutation Approaches](#mutation-approaches)
98- [Mutation Lifecycle](#mutation-lifecycle)
99- [Collection Write Operations](#collection-write-operations)
100- [Operation Handlers](#operation-handlers)
101- [Creating Custom Actions](#creating-custom-actions)
102- [Manual Transactions](#manual-transactions)
103- [Mutation Merging](#mutation-merging)
104- [Controlling Optimistic Behavior](#controlling-optimistic-behavior)
105- [Transaction States](#transaction-states)
106- [Handling Temporary IDs](#handling-temporary-ids)
107
108## Mutation Approaches
109
110TanStack DB provides different approaches to mutations, each suited to different use cases:
111
112### Collection-Level Mutations
113
114Collection-level mutations (`insert`, `update`, `delete`) are designed for **direct state manipulation** of a single collection. These are the simplest way to make changes and work well for straightforward CRUD operations.
115
116```tsx
117// Direct state change
118todoCollection.update(todoId, (draft) => {
119 draft.completed = true
120 draft.completedAt = new Date()
121})
122```
123
124Use collection-level mutations when:
125- You're making simple CRUD operations on a single collection
126- The state changes are straightforward and match what the server will store
127
128You can use `metadata` to annotate these operations and customize behavior in your handlers:
129
130```tsx
131// Annotate with metadata
132todoCollection.update(
133 todoId,
134 { metadata: { intent: 'complete' } },
135 (draft) => {
136 draft.completed = true
137 }
138)
139
140// Use metadata in handler
141onUpdate: async ({ transaction }) => {
142 const mutation = transaction.mutations[0]
143
144 if (mutation.metadata?.intent === 'complete') {
145 await Promise.all(
146 transaction.mutations.map((mutation) =>
147 api.todos.complete(mutation.original.id)
148 )
149 )
150 } else {
151 await Promise.all(
152 transaction.mutations.map((mutation) =>
153 api.todos.update(mutation.original.id, mutation.changes)
154 )
155 )
156 }
157}
158```
159
160### Intent-Based Mutations with Custom Actions
161
162For more complex scenarios, use `createOptimisticAction` or `createTransaction` to create **intent-based mutations** that capture specific user actions.
163
164```tsx
165// Intent: "like this post"
166const likePost = createOptimisticAction<string>({
167 onMutate: (postId) => {
168 // Optimistic guess at the change
169 postCollection.update(postId, (draft) => {
170 draft.likeCount += 1
171 draft.likedByMe = true
172 })
173 },
174 mutationFn: async (postId) => {
175 // Send the intent to the server
176 await api.posts.like(postId)
177 // Server determines actual state changes
178 await postCollection.utils.refetch()
179 },
180})
181
182// Use it.
183likePost(postId)
184```
185
186Use custom actions when:
187- You need to mutate **multiple collections** in a single transaction
188- The optimistic change is a **guess** at how the server will transform the data
189- You want to send **user intent** to the backend rather than exact state changes
190- The server performs complex logic, calculations, or side effects
191- You want a clean, reusable mutation that captures a specific operation
192
193Custom actions provide the cleanest way to capture specific types of mutations as named operations in your application. While you can achieve similar results using metadata with collection-level mutations, custom actions make the intent explicit and keep related logic together.
194
195**When to use each:**
196
197- **Collection-level mutations** (`collection.update`): Simple CRUD operations on a single collection
198- **`createOptimisticAction`**: Intent-based operations, multi-collection mutations, immediately committed
199- **`createTransaction`**: Fully custom transactions, delayed commits, multi-step workflows
200
201## Mutation Lifecycle
202
203The mutation lifecycle follows a consistent pattern across all mutation types:
204
2051. **Optimistic state applied**: The mutation is immediately applied to the local collection as optimistic state
2062. **Handler invoked**: The appropriate handler — either `mutationFn` or a Collection handler (`onInsert`, `onUpdate`, or `onDelete`) — is called to persist the change
2073. **Backend persistence**: Your handler persists the data to your backend
2084. **Sync back**: The handler ensures server writes have synced back to the collection
2095. **Optimistic state dropped**: Once synced, the optimistic state is replaced by the confirmed server state
210
211```tsx
212// Step 1: Optimistic state applied immediately
213todoCollection.update(todo.id, (draft) => {
214 draft.completed = true
215})
216// UI updates instantly with optimistic state
217
218// Step 2-3: onUpdate handler persists to backend
219// Step 4: Handler waits for sync back
220// Step 5: Optimistic state replaced by server state
221```
222
223If the handler throws an error during persistence, the optimistic state is automatically rolled back.
224
225## Collection Write Operations
226
227Collections support three core write operations: `insert`, `update`, and `delete`. Each operation applies optimistic state immediately and triggers the corresponding operation handler.
228
229### Insert
230
231Add new items to a collection:
232
233```typescript
234// Insert a single item
235todoCollection.insert({
236 id: "1",
237 text: "Buy groceries",
238 completed: false
239})
240
241// Insert multiple items
242todoCollection.insert([
243 { id: "1", text: "Buy groceries", completed: false },
244 { id: "2", text: "Walk dog", completed: false },
245])
246
247// Insert with metadata
248todoCollection.insert(
249 { id: "1", text: "Custom item", completed: false },
250 { metadata: { source: "import" } }
251)
252
253// Insert without optimistic updates
254todoCollection.insert(
255 { id: "1", text: "Server-validated item", completed: false },
256 { optimistic: false }
257)
258```
259
260**Returns**: A `Transaction` object that you can use to track the mutation's lifecycle.
261
262### Update
263
264Modify existing items using an immutable draft pattern:
265
266```typescript
267// Update a single item
268todoCollection.update(todo.id, (draft) => {
269 draft.completed = true
270})
271
272// Update multiple items
273todoCollection.update([todo1.id, todo2.id], (drafts) => {
274 drafts.forEach((draft) => {
275 draft.completed = true
276 })
277})
278
279// Update with metadata
280todoCollection.update(
281 todo.id,
282 { metadata: { reason: "user update" } },
283 (draft) => {
284 draft.text = "Updated text"
285 }
286)
287
288// Update without optimistic updates
289todoCollection.update(
290 todo.id,
291 { optimistic: false },
292 (draft) => {
293 draft.status = "server-validated"
294 }
295)
296```
297
298**Parameters**:
299- `key` or `keys`: The item key(s) to update
300- `options` (optional): Configuration object with `metadata` and/or `optimistic` flags
301- `updater`: Function that receives a draft to mutate
302
303**Returns**: A `Transaction` object that you can use to track the mutation's lifecycle.
304
305> [!IMPORTANT]
306> The `updater` function uses an Immer-like pattern to capture changes as immutable updates. You must not reassign the draft parameter itself—only mutate its properties.
307
308### Delete
309
310Remove items from a collection:
311
312```typescript
313// Delete a single item
314todoCollection.delete(todo.id)
315
316// Delete multiple items
317todoCollection.delete([todo1.id, todo2.id])
318
319// Delete with metadata
320todoCollection.delete(todo.id, {
321 metadata: { reason: "completed" }
322})
323
324// Delete without optimistic updates
325todoCollection.delete(todo.id, { optimistic: false })
326```
327
328**Parameters**:
329- `key` or `keys`: The item key(s) to delete
330- `options` (optional): Configuration object with `metadata` and/or `optimistic` flags
331
332**Returns**: A `Transaction` object that you can use to track the mutation's lifecycle.
333
334## Operation Handlers
335
336Operation handlers are functions you provide when creating a collection that handle persisting mutations to your backend. Each collection can define three optional handlers: `onInsert`, `onUpdate`, and `onDelete`.
337
338### Handler Signature
339
340All operation handlers receive an object with the following properties:
341
342```typescript
343type OperationHandler = (params: {
344 transaction: Transaction
345 collection: Collection
346}) => Promise<any> | any
347```
348
349The `transaction` object contains:
350- `mutations`: Array of mutation objects, each with:
351 - `collection`: The collection being mutated
352 - `type`: The mutation type (`'insert'`, `'update'`, or `'delete'`)
353 - `original`: The original item (for updates and deletes)
354 - `modified`: The modified item (for inserts and updates)
355 - `changes`: The changes object (for updates)
356 - `key`: The item key
357 - `metadata`: Optional metadata attached to the mutation
358
359### Defining Operation Handlers
360
361Define handlers when creating a collection:
362
363```typescript
364const todoCollection = createCollection({
365 id: "todos",
366 // ... other options
367
368 onInsert: async ({ transaction }) => {
369 await Promise.all(
370 transaction.mutations.map((mutation) =>
371 api.todos.create(mutation.modified)
372 )
373 )
374 },
375
376 onUpdate: async ({ transaction }) => {
377 await Promise.all(
378 transaction.mutations.map((mutation) =>
379 api.todos.update(mutation.original.id, mutation.changes)
380 )
381 )
382 },
383
384 onDelete: async ({ transaction }) => {
385 await Promise.all(
386 transaction.mutations.map((mutation) =>
387 api.todos.delete(mutation.original.id)
388 )
389 )
390 },
391})
392```
393
394> [!IMPORTANT]
395> Operation handlers must not resolve until the server changes have synced back to the collection. Different collection types provide different patterns to ensure this happens correctly.
396
397### Collection-Specific Handler Patterns
398
399Different collection types have specific patterns for their handlers:
400
401**QueryCollection** - automatically refetches after handler completes:
402```typescript
403onUpdate: async ({ transaction }) => {
404 await Promise.all(
405 transaction.mutations.map((mutation) =>
406 api.todos.update(mutation.original.id, mutation.changes)
407 )
408 )
409 // Automatic refetch happens after handler completes
410}
411```
412
413**ElectricCollection** - return txid(s) to track sync:
414```typescript
415onUpdate: async ({ transaction }) => {
416 const txids = await Promise.all(
417 transaction.mutations.map(async (mutation) => {
418 const response = await api.todos.update(mutation.original.id, mutation.changes)
419 return response.txid
420 })
421 )
422 return { txid: txids }
423}
424```
425
426### Generic Mutation Functions
427
428You can define a single mutation function for your entire app:
429
430```typescript
431import type { MutationFn } from "@tanstack/react-db"
432
433const mutationFn: MutationFn = async ({ transaction }) => {
434 const response = await api.mutations.batch(transaction.mutations)
435
436 if (!response.ok) {
437 throw new Error(`HTTP Error: ${response.status}`)
438 }
439}
440
441// Use in collections
442const todoCollection = createCollection({
443 id: "todos",
444 onInsert: mutationFn,
445 onUpdate: mutationFn,
446 onDelete: mutationFn,
447})
448```
449
450## Creating Custom Actions
451
452For more complex mutation patterns, use `createOptimisticAction` to create custom actions with full control over the mutation lifecycle.
453
454### Basic Action
455
456Create an action that combines mutation logic with persistence:
457
458```tsx
459import { createOptimisticAction } from "@tanstack/react-db"
460
461const addTodo = createOptimisticAction<string>({
462 onMutate: (text) => {
463 // Apply optimistic state
464 todoCollection.insert({
465 id: crypto.randomUUID(),
466 text,
467 completed: false,
468 })
469 },
470 mutationFn: async (text, params) => {
471 // Persist to backend
472 const response = await fetch("/api/todos", {
473 method: "POST",
474 body: JSON.stringify({ text, completed: false }),
475 })
476 const result = await response.json()
477
478 // Wait for sync back
479 await todoCollection.utils.refetch()
480
481 return result
482 },
483})
484
485// Use in components
486const Todo = () => {
487 const handleClick = () => {
488 addTodo("🔥 Make app faster")
489 }
490
491 return <Button onClick={handleClick} />
492}
493```
494
495### Complex Multi-Collection Actions
496
497Actions can mutate multiple collections:
498
499```tsx
500const createProject = createOptimisticAction<{
501 name: string
502 ownerId: string
503}>({
504 onMutate: ({ name, ownerId }) => {
505 const projectId = crypto.randomUUID()
506
507 // Insert project
508 projectCollection.insert({
509 id: projectId,
510 name,
511 ownerId,
512 createdAt: new Date(),
513 })
514
515 // Update user's project count
516 userCollection.update(ownerId, (draft) => {
517 draft.projectCount += 1
518 })
519 },
520 mutationFn: async ({ name, ownerId }) => {
521 const response = await api.projects.create({ name, ownerId })
522
523 // Wait for both collections to sync
524 await Promise.all([
525 projectCollection.utils.refetch(),
526 userCollection.utils.refetch(),
527 ])
528
529 return response
530 },
531})
532```
533
534### Action Parameters
535
536The `mutationFn` receives additional parameters for advanced use cases:
537
538```tsx
539const updateTodo = createOptimisticAction<{
540 id: string
541 changes: Partial<Todo>
542}>({
543 onMutate: ({ id, changes }) => {
544 todoCollection.update(id, (draft) => {
545 Object.assign(draft, changes)
546 })
547 },
548 mutationFn: async ({ id, changes }, params) => {
549 // params.transaction contains the transaction object
550 // params.signal is an AbortSignal for cancellation
551
552 const response = await api.todos.update(id, changes, {
553 signal: params.signal,
554 })
555
556 await todoCollection.utils.refetch()
557 return response
558 },
559})
560```
561
562## Manual Transactions
563
564For maximum control over transaction lifecycles, create transactions manually using `createTransaction`. This approach allows you to batch multiple mutations, implement custom commit workflows, or create transactions that span multiple user interactions.
565
566### Basic Manual Transaction
567
568```ts
569import { createTransaction } from "@tanstack/react-db"
570
571const addTodoTx = createTransaction({
572 autoCommit: false,
573 mutationFn: async ({ transaction }) => {
574 // Persist all mutations to backend
575 await Promise.all(
576 transaction.mutations.map((mutation) =>
577 api.saveTodo(mutation.modified)
578 )
579 )
580 },
581})
582
583// Apply first change
584addTodoTx.mutate(() =>
585 todoCollection.insert({
586 id: "1",
587 text: "First todo",
588 completed: false
589 })
590)
591
592// User reviews change...
593
594// Apply another change
595addTodoTx.mutate(() =>
596 todoCollection.insert({
597 id: "2",
598 text: "Second todo",
599 completed: false
600 })
601)
602
603// User commits when ready (e.g., when they hit save)
604addTodoTx.commit()
605```
606
607### Transaction Configuration
608
609Manual transactions accept the following options:
610
611```typescript
612createTransaction({
613 id?: string, // Optional unique identifier for the transaction
614 autoCommit?: boolean, // Whether to automatically commit after mutate()
615 mutationFn: MutationFn, // Function to persist mutations
616 metadata?: Record<string, unknown>, // Optional custom metadata
617})
618```
619
620**autoCommit**:
621- `true` (default): Transaction commits immediately after each `mutate()` call
622- `false`: Transaction waits for explicit `commit()` call
623
624### Transaction Methods
625
626Manual transactions provide several methods:
627
628```typescript
629// Apply mutations within a transaction
630tx.mutate(() => {
631 collection.insert(item)
632 collection.update(key, updater)
633})
634
635// Commit the transaction
636await tx.commit()
637
638// Manually rollback changes (e.g., user cancels a form)
639// Note: Rollback happens automatically if mutationFn throws an error
640tx.rollback()
641```
642
643### Multi-Step Workflows
644
645Manual transactions excel at complex workflows:
646
647```ts
648const reviewTx = createTransaction({
649 autoCommit: false,
650 mutationFn: async ({ transaction }) => {
651 await api.batchUpdate(transaction.mutations)
652 },
653})
654
655// Step 1: User makes initial changes
656reviewTx.mutate(() => {
657 todoCollection.update(id1, (draft) => {
658 draft.status = "reviewed"
659 })
660 todoCollection.update(id2, (draft) => {
661 draft.status = "reviewed"
662 })
663})
664
665// Step 2: Show preview to user...
666
667// Step 3: User confirms or makes additional changes
668reviewTx.mutate(() => {
669 todoCollection.update(id3, (draft) => {
670 draft.status = "reviewed"
671 })
672})
673
674// Step 4: User commits all changes at once
675await reviewTx.commit()
676// OR user cancels
677// reviewTx.rollback()
678```
679
680### Listening to Transaction Lifecycle
681
682Monitor transaction state changes:
683
684```typescript
685const tx = createTransaction({
686 autoCommit: false,
687 mutationFn: async ({ transaction }) => {
688 await api.persist(transaction.mutations)
689 },
690})
691
692// Wait for transaction to complete
693tx.isPersisted.promise.then(() => {
694 console.log("Transaction persisted!")
695})
696
697// Check current state
698console.log(tx.state) // 'pending', 'persisting', 'completed', or 'failed'
699```
700
701## Mutation Merging
702
703When multiple mutations operate on the same item within a transaction, TanStack DB intelligently merges them to:
704- **Reduce network traffic**: Fewer mutations sent to the server
705- **Preserve user intent**: Final state matches what user expects
706- **Maintain UI consistency**: Local state always reflects user actions
707
708The merging behavior follows a truth table based on the mutation types:
709
710| Existing → New | Result | Description |
711| ------------------- | --------- | ------------------------------------------------- |
712| **insert + update** | `insert` | Keeps insert type, merges changes, empty original |
713| **insert + delete** | _removed_ | Mutations cancel each other out |
714| **update + delete** | `delete` | Delete dominates |
715| **update + update** | `update` | Union changes, keep first original |
716
717> [!NOTE]
718> Attempting to insert or delete the same item multiple times within a transaction will throw an error.
719
720## Controlling Optimistic Behavior
721
722By default, all mutations apply optimistic updates immediately to provide instant feedback. However, you can disable this behavior when you need to wait for server confirmation before applying changes locally.
723
724### When to Disable Optimistic Updates
725
726Consider using `optimistic: false` when:
727
728- **Complex server-side processing**: Operations that depend on server-side generation (e.g., cascading foreign keys, computed fields)
729- **Validation requirements**: Operations where backend validation might reject the change
730- **Confirmation workflows**: Deletes where UX should wait for confirmation before removing data
731- **Batch operations**: Large operations where optimistic rollback would be disruptive
732
733### Behavior Differences
734
735**`optimistic: true` (default)**:
736- Immediately applies mutation to the local store
737- Provides instant UI feedback
738- Requires rollback if server rejects the mutation
739- Best for simple, predictable operations
740
741**`optimistic: false`**:
742- Does not modify local store until server confirms
743- No immediate UI feedback, but no rollback needed
744- UI updates only after successful server response
745- Best for complex or validation-heavy operations
746
747### Using Non-Optimistic Mutations
748
749```typescript
750// Critical deletion that needs confirmation
751const handleDeleteAccount = () => {
752 userCollection.delete(userId, { optimistic: false })
753}
754
755// Server-generated data
756const handleCreateInvoice = () => {
757 // Server generates invoice number, tax calculations, etc.
758 invoiceCollection.insert(invoiceData, { optimistic: false })
759}
760
761// Mixed approach in same transaction
762tx.mutate(() => {
763 // Instant UI feedback for simple change
764 todoCollection.update(todoId, (draft) => {
765 draft.completed = true
766 })
767
768 // Wait for server confirmation for complex change
769 auditCollection.insert(auditRecord, { optimistic: false })
770})
771```
772
773### Waiting for Persistence
774
775A common pattern with `optimistic: false` is to wait for the mutation to complete before navigating or showing success feedback:
776
777```typescript
778const handleCreatePost = async (postData) => {
779 // Insert without optimistic updates
780 const tx = postsCollection.insert(postData, { optimistic: false })
781
782 try {
783 // Wait for write to server and sync back to complete
784 await tx.isPersisted.promise
785
786 // Server write and sync back were successful
787 navigate(`/posts/${postData.id}`)
788 } catch (error) {
789 // Show error notification
790 toast.error("Failed to create post: " + error.message)
791 }
792}
793
794// Works with updates and deletes too
795const handleUpdateTodo = async (todoId, changes) => {
796 const tx = todoCollection.update(
797 todoId,
798 { optimistic: false },
799 (draft) => Object.assign(draft, changes)
800 )
801
802 try {
803 await tx.isPersisted.promise
804 navigate("/todos")
805 } catch (error) {
806 toast.error("Failed to update todo: " + error.message)
807 }
808}
809```
810
811## Transaction States
812
813Transactions progress through the following states during their lifecycle:
814
8151. **`pending`**: Initial state when a transaction is created and optimistic mutations can be applied
8162. **`persisting`**: Transaction is being persisted to the backend
8173. **`completed`**: Transaction has been successfully persisted and any backend changes have been synced back
8184. **`failed`**: An error was thrown while persisting or syncing back the transaction
819
820### Monitoring Transaction State
821
822```typescript
823const tx = todoCollection.update(todoId, (draft) => {
824 draft.completed = true
825})
826
827// Check current state
828console.log(tx.state) // 'pending'
829
830// Wait for specific states
831await tx.isPersisted.promise
832console.log(tx.state) // 'completed' or 'failed'
833
834// Handle errors
835try {
836 await tx.isPersisted.promise
837 console.log("Success!")
838} catch (error) {
839 console.log("Failed:", error)
840}
841```
842
843### State Transitions
844
845The normal flow is: `pending` → `persisting` → `completed`
846
847If an error occurs: `pending` → `persisting` → `failed`
848
849Failed transactions automatically rollback their optimistic state.
850
851## Handling Temporary IDs
852
853When inserting new items into collections where the server generates the final ID, you'll need to handle the transition from temporary to real IDs carefully to avoid UI issues and operation failures.
854
855### The Problem
856
857When you insert an item with a temporary ID, the optimistic object is eventually replaced by the synced object with its real server-generated ID. This can cause two issues:
858
8591. **UI Flicker**: Your UI framework may unmount and remount components when the key changes from temporary to real ID
8602. **Subsequent Operations**: Operations like delete may fail if they try to use the temporary ID before the real ID syncs back
861
862```tsx
863// Generate temporary ID (e.g., negative number)
864const tempId = -(Math.floor(Math.random() * 1000000) + 1)
865
866// Insert with temporary ID
867todoCollection.insert({
868 id: tempId,
869 text: "New todo",
870 completed: false
871})
872
873// Problem 1: UI may re-render when tempId is replaced with real ID
874// Problem 2: Trying to delete before sync completes will use tempId
875todoCollection.delete(tempId) // May 404 on backend
876```
877
878### Solution 1: Use Client-Generated UUIDs
879
880If your backend supports client-generated IDs, use UUIDs to eliminate the temporary ID problem entirely:
881
882```tsx
883// Generate UUID on client
884const id = crypto.randomUUID()
885
886todoCollection.insert({
887 id,
888 text: "New todo",
889 completed: false
890})
891
892// No flicker - the ID is stable
893// Subsequent operations work immediately
894todoCollection.delete(id) // Works with the same ID
895```
896
897This is the cleanest approach when your backend supports it, as the ID never changes.
898
899### Solution 2: Wait for Persistence or Use Non-Optimistic Inserts
900
901Wait for the mutation to persist before allowing subsequent operations, or use non-optimistic inserts to avoid showing the item until the real ID is available:
902
903```tsx
904const handleCreateTodo = async (text: string) => {
905 const tempId = -Math.floor(Math.random() * 1000000) + 1
906
907 const tx = todoCollection.insert({
908 id: tempId,
909 text,
910 completed: false
911 })
912
913 // Wait for persistence to complete
914 await tx.isPersisted.promise
915
916 // Now we have the real ID from the server
917 // Subsequent operations will use the real ID
918}
919
920// Disable delete buttons until persisted
921const TodoItem = ({ todo, isPersisted }: { todo: Todo, isPersisted: boolean }) => {
922 return (
923 <div>
924 {todo.text}
925 <button
926 onClick={() => todoCollection.delete(todo.id)}
927 disabled={!isPersisted}
928 >
929 Delete
930 </button>
931 </div>
932 )
933}
934```
935
936### Solution 3: Maintain a View Key Mapping
937
938To avoid UI flicker while keeping optimistic updates, maintain a separate mapping from IDs (both temporary and real) to stable view keys:
939
940```tsx
941// Create a mapping API
942const idToViewKey = new Map<number | string, string>()
943
944function getViewKey(id: number | string): string {
945 if (!idToViewKey.has(id)) {
946 idToViewKey.set(id, crypto.randomUUID())
947 }
948 return idToViewKey.get(id)!
949}
950
951function linkIds(tempId: number, realId: number) {
952 const viewKey = getViewKey(tempId)
953 idToViewKey.set(realId, viewKey)
954}
955
956// Configure collection to link IDs when real ID comes back
957const todoCollection = createCollection({
958 id: "todos",
959 // ... other options
960 onInsert: async ({ transaction }) => {
961 const mutation = transaction.mutations[0]
962 const tempId = mutation.modified.id
963
964 // Create todo on server and get real ID back
965 const response = await api.todos.create({
966 text: mutation.modified.text,
967 completed: mutation.modified.completed,
968 })
969 const realId = response.id
970
971 // Link temp ID to same view key as real ID
972 linkIds(tempId, realId)
973
974 // Wait for sync back
975 await todoCollection.utils.refetch()
976 },
977})
978
979// When inserting with temp ID
980const tempId = -Math.floor(Math.random() * 1000000) + 1
981const viewKey = getViewKey(tempId) // Creates and stores mapping
982
983todoCollection.insert({
984 id: tempId,
985 text: "New todo",
986 completed: false
987})
988
989// Use view key for rendering
990const TodoList = () => {
991 const { data: todos } = useLiveQuery((q) =>
992 q.from({ todo: todoCollection })
993 )
994
995 return (
996 <ul>
997 {todos.map((todo) => (
998 <li key={getViewKey(todo.id)}> {/* Stable key */}
999 {todo.text}
1000 </li>
1001 ))}
1002 </ul>
1003 )
1004}
1005```
1006
1007This pattern maintains a stable key throughout the temporary → real ID transition, preventing your UI framework from unmounting and remounting the component. The view key is stored outside the collection items, so you don't need to add extra fields to your data model.
1008
1009### Best Practices
1010
10111. **Use UUIDs when possible**: Client-generated UUIDs eliminate the temporary ID problem
10122. **Generate temporary IDs deterministically**: Use negative numbers or a specific pattern to distinguish temporary IDs from real ones
10133. **Disable operations on temporary items**: Disable delete/update buttons until persistence completes
10144. **Maintain view key mappings**: Create a mapping between IDs and stable view keys for rendering
1015
1016> [!NOTE]
1017> There's an [open issue](https://github.com/TanStack/db/issues/19) to add better built-in support for temporary ID handling in TanStack DB. This would automate the view key pattern and make it easier to work with server-generated IDs.