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