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

createoptimisticaction.md

77 lines1.8 KB

1---
2id: createOptimisticAction
3title: createOptimisticAction
4---
5​
6<!-- DO NOT EDIT: this page is autogenerated from the type comments -->
7​
8# Function: createOptimisticAction()
9​
10```ts
11function createOptimisticAction<TVariables>(options): (variables) => Transaction
12```
13​
14Defined in: [packages/db/src/optimistic-action.ts:41](https://github.com/TanStack/db/blob/main/packages/db/src/optimistic-action.ts#L41)
15​
16Creates an optimistic action function that applies local optimistic updates immediately
17before executing the actual mutation on the server.
18​
19This pattern allows for responsive UI updates while the actual mutation is in progress.
20The optimistic update is applied via the `onMutate` callback, and the server mutation
21is executed via the `mutationFn`.
22​
23## Type Parameters
24​
25• **TVariables** = `unknown`
26​
27The type of variables that will be passed to the action function
28​
29## Parameters
30​
31### options
32​
33[`CreateOptimisticActionsOptions`](../../interfaces/createoptimisticactionsoptions.md)\<`TVariables`\>
34​
35Configuration options for the optimistic action
36​
37## Returns
38​
39`Function`
40​
41A function that accepts variables of type TVariables and returns a Transaction
42​
43### Parameters
44​
45#### variables
46​
47`TVariables`
48​
49### Returns
50​
51[`Transaction`](../../classes/transaction.md)
52​
53## Example
54​
55```ts
56const addTodo = createOptimisticAction<string>({
57 onMutate: (text) => {
58 // Instantly applies local optimistic state
59 todoCollection.insert({
60 id: uuid(),
61 text,
62 completed: false
63 })
64 },
65 mutationFn: async (text, params) => {
66 // Persist the todo to your backend
67 const response = await fetch('/api/todos', {
68 method: 'POST',
69 body: JSON.stringify({ text, completed: false }),
70 })
71 return response.json()
72 }
73})
74​
75// Usage
76const transaction = addTodo('New Todo Item')
77```