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

optimistic-updates.md

146 lines3.9 KB

1---
2id: optimistic-updates
3title: Optimistic Updates
4ref: docs/framework/react/guides/optimistic-updates.md
5replace: { 'React Query': 'Solid Query', 'hook': 'primitive' }
6---
7​
8[//]: # 'ExampleUI1'
9​
10```tsx
11const addTodoMutation = useMutation(() => ({
12 mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
13 // make sure to _return_ the Promise from the query invalidation
14 // so that the mutation stays in `pending` state until the refetch is finished
15 onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
16}))
17```
18​
19[//]: # 'ExampleUI1'
20[//]: # 'ExampleUI2'
21​
22```tsx
23<ul>
24 <For each={todoQuery.data}>{(todo) => <li>{todo.text}</li>}</For>
25 <Show when={addTodoMutation.isPending}>
26 <li style={{ opacity: 0.5 }}>{addTodoMutation.variables}</li>
27 </Show>
28</ul>
29```
30​
31[//]: # 'ExampleUI2'
32[//]: # 'ExampleUI3'
33​
34```tsx
35<Show when={addTodoMutation.isError}>
36 <li style={{ color: 'red' }}>
37 {addTodoMutation.variables}
38 <button onClick={() => addTodoMutation.mutate(addTodoMutation.variables)}>
39 Retry
40 </button>
41 </li>
42</Show>
43```
44​
45[//]: # 'ExampleUI3'
46[//]: # 'ExampleUI4'
47​
48```tsx
49// somewhere in your app
50const mutation = useMutation(() => ({
51 mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
52 onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
53 mutationKey: ['addTodo'],
54}))
55​
56// access variables somewhere else
57const variables = useMutationState(() => ({
58 filters: { mutationKey: ['addTodo'], status: 'pending' },
59 select: (mutation) => mutation.state.variables,
60}))
61```
62​
63[//]: # 'ExampleUI4'
64[//]: # 'Example'
65​
66```tsx
67const queryClient = useQueryClient()
68​
69useMutation(() => ({
70 mutationFn: updateTodo,
71 // When mutate is called:
72 onMutate: async (newTodo, context) => {
73 // Cancel any outgoing refetches
74 // (so they don't overwrite our optimistic update)
75 await context.client.cancelQueries({ queryKey: ['todos'] })
76​
77 // Snapshot the previous value
78 const previousTodos = context.client.getQueryData(['todos'])
79​
80 // Optimistically update to the new value
81 context.client.setQueryData(['todos'], (old) => [...old, newTodo])
82​
83 // Return a result with the snapshotted value
84 return { previousTodos }
85 },
86 // If the mutation fails,
87 // use the result returned from onMutate to roll back
88 onError: (err, newTodo, onMutateResult, context) => {
89 context.client.setQueryData(['todos'], onMutateResult.previousTodos)
90 },
91 // Always refetch after error or success:
92 onSettled: (data, error, variables, onMutateResult, context) =>
93 context.client.invalidateQueries({ queryKey: ['todos'] }),
94}))
95```
96​
97[//]: # 'Example'
98[//]: # 'Example2'
99​
100```tsx
101useMutation(() => ({
102 mutationFn: updateTodo,
103 // When mutate is called:
104 onMutate: async (newTodo, context) => {
105 // Cancel any outgoing refetches
106 // (so they don't overwrite our optimistic update)
107 await context.client.cancelQueries({ queryKey: ['todos', newTodo.id] })
108​
109 // Snapshot the previous value
110 const previousTodo = context.client.getQueryData(['todos', newTodo.id])
111​
112 // Optimistically update to the new value
113 context.client.setQueryData(['todos', newTodo.id], newTodo)
114​
115 // Return a result with the previous and new todo
116 return { previousTodo, newTodo }
117 },
118 // If the mutation fails, use the result we returned above
119 onError: (err, newTodo, onMutateResult, context) => {
120 context.client.setQueryData(
121 ['todos', onMutateResult.newTodo.id],
122 onMutateResult.previousTodo,
123 )
124 },
125 // Always refetch after error or success:
126 onSettled: (newTodo, error, variables, onMutateResult, context) =>
127 context.client.invalidateQueries({ queryKey: ['todos', newTodo.id] }),
128}))
129```
130​
131[//]: # 'Example2'
132[//]: # 'Example3'
133​
134```tsx
135useMutation(() => ({
136 mutationFn: updateTodo,
137 // ...
138 onSettled: async (newTodo, error, variables, onMutateResult, context) => {
139 if (error) {
140 // do something
141 }
142 },
143}))
144```
145​
146[//]: # 'Example3'