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

createOptimisticAction.md

90 lines2.3 KB

1---
2id: createOptimisticAction
3title: createOptimisticAction
4---
5​
6# Function: createOptimisticAction()
7​
8```ts
9function createOptimisticAction<TVariables>(options): (variables) => Transaction;
10```
11​
12Defined in: [packages/db/src/optimistic-action.ts:54](https://github.com/TanStack/db/blob/main/packages/db/src/optimistic-action.ts#L54)
13​
14Creates an optimistic action function that applies local optimistic updates immediately
15before executing the actual mutation on the server.
16​
17This pattern allows for responsive UI updates while the actual mutation is in progress.
18The optimistic update is applied via the `onMutate` callback, and the server mutation
19is executed via the `mutationFn`.
20​
21**Important:** Inside your `mutationFn`, you must ensure that your server writes have synced back
22before you return, as the optimistic state is dropped when you return from the mutation function.
23You generally use collection-specific helpers to do this, such as Query's `utils.refetch()`,
24direct write APIs, or Electric's `utils.awaitTxId()`.
25​
26## Type Parameters
27​
28### TVariables
29​
30`TVariables` = `unknown`
31​
32The type of variables that will be passed to the action function
33​
34## Parameters
35​
36### options
37​
38[`CreateOptimisticActionsOptions`](../interfaces/CreateOptimisticActionsOptions.md)\<`TVariables`\>
39​
40Configuration options for the optimistic action
41​
42## Returns
43​
44A function that accepts variables of type TVariables and returns a Transaction
45​
46```ts
47(variables): Transaction;
48```
49​
50### Parameters
51​
52#### variables
53​
54`TVariables`
55​
56### Returns
57​
58[`Transaction`](../interfaces/Transaction.md)
59​
60## Example
61​
62```ts
63const addTodo = createOptimisticAction<string>({
64 onMutate: (text) => {
65 // Instantly applies local optimistic state
66 todoCollection.insert({
67 id: uuid(),
68 text,
69 completed: false
70 })
71 },
72 mutationFn: async (text, params) => {
73 // Persist the todo to your backend
74 const response = await fetch('/api/todos', {
75 method: 'POST',
76 body: JSON.stringify({ text, completed: false }),
77 })
78 const result = await response.json()
79​
80 // IMPORTANT: Ensure server writes have synced back before returning
81 // This ensures the optimistic state can be safely discarded
82 await todoCollection.utils.refetch()
83​
84 return result
85 }
86})
87​
88// Usage
89const transaction = addTodo('New Todo Item')
90```