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

optimistic-updates.md

196 lines6.9 KB

1---
2id: optimistic-updates
3title: Optimistic Updates
4---
5​
6React Query provides two ways to optimistically update your UI before a mutation has completed. You can either use the `onMutate` option to update your cache directly, or leverage the returned `variables` to update your UI from the `useMutation` result.
7​
8## Via the UI
9​
10This is the simpler variant, as it doesn't interact with the cache directly.
11​
12[//]: # 'ExampleUI1'
13​
14```tsx
15const addTodoMutation = useMutation({
16 mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
17 // make sure to _return_ the Promise from the query invalidation
18 // so that the mutation stays in `pending` state until the refetch is finished
19 onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
20})
21​
22const { isPending, submittedAt, variables, mutate, isError } = addTodoMutation
23```
24​
25[//]: # 'ExampleUI1'
26​
27you will then have access to `addTodoMutation.variables`, which contain the added todo. In your UI list, where the query is rendered, you can append another item to the list while the mutation `isPending`:
28​
29[//]: # 'ExampleUI2'
30​
31```tsx
32<ul>
33 {todoQuery.items.map((todo) => (
34 <li key={todo.id}>{todo.text}</li>
35 ))}
36 {isPending && <li style={{ opacity: 0.5 }}>{variables}</li>}
37</ul>
38```
39​
40[//]: # 'ExampleUI2'
41​
42We're rendering a temporary item with a different `opacity` as long as the mutation is pending. Once it completes, the item will automatically no longer be rendered. Given that the refetch succeeded, we should see the item as a "normal item" in our list.
43​
44If the mutation errors, the item will also disappear. But we could continue to show it, if we want, by checking for the `isError` state of the mutation. `variables` are _not_ cleared when the mutation errors, so we can still access them, maybe even show a retry button:
45​
46[//]: # 'ExampleUI3'
47​
48```tsx
50 isError && (
51 <li style={{ color: 'red' }}>
52 {variables}
53 <button onClick={() => mutate(variables)}>Retry</button>
54 </li>
55 )
57```
58​
59[//]: # 'ExampleUI3'
60​
61### If the mutation and the query don't live in the same component
62​
63This approach works very well if the mutation and the query live in the same component. However, you also get access to all mutations in other components via the dedicated `useMutationState` hook. It is best combined with a `mutationKey`:
64​
65[//]: # 'ExampleUI4'
66​
67```tsx
68// somewhere in your app
69const { mutate } = useMutation({
70 mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
71 onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
72 mutationKey: ['addTodo'],
73})
74​
75// access variables somewhere else
76const variables = useMutationState<string>({
77 filters: { mutationKey: ['addTodo'], status: 'pending' },
78 select: (mutation) => mutation.state.variables,
79})
80```
81​
82[//]: # 'ExampleUI4'
83​
84`variables` will be an `Array`, because there might be multiple mutations running at the same time. If we need a unique key for the items, we can also select `mutation.state.submittedAt`. This will even make displaying concurrent optimistic updates a breeze.
85​
86## Via the cache
87​
88When you optimistically update your state before performing a mutation, there is a chance that the mutation will fail. In most of these failure cases, you can just trigger a refetch for your optimistic queries to revert them to their true server state. In some circumstances though, refetching may not work correctly and the mutation error could represent some type of server issue that won't make it possible to refetch. In this event, you can instead choose to roll back your update.
89​
90To do this, `useMutation`'s `onMutate` handler option allows you to return a value that will later be passed to both `onError` and `onSettled` handlers as the last argument. In most cases, it is most useful to pass a rollback function.
91​
92### Updating a list of todos when adding a new todo
93​
94[//]: # 'Example'
95​
96```tsx
97const queryClient = useQueryClient()
98​
99useMutation({
100 mutationFn: updateTodo,
101 // When mutate is called:
102 onMutate: async (newTodo, context) => {
103 // Cancel any outgoing refetches
104 // (so they don't overwrite our optimistic update)
105 await context.client.cancelQueries({ queryKey: ['todos'] })
106​
107 // Snapshot the previous value
108 const previousTodos = context.client.getQueryData(['todos'])
109​
110 // Optimistically update to the new value
111 context.client.setQueryData(['todos'], (old) => [...old, newTodo])
112​
113 // Return a result with the snapshotted value
114 return { previousTodos }
115 },
116 // If the mutation fails,
117 // use the result returned from onMutate to roll back
118 onError: (err, newTodo, onMutateResult, context) => {
119 context.client.setQueryData(['todos'], onMutateResult.previousTodos)
120 },
121 // Always refetch after error or success:
122 onSettled: (data, error, variables, onMutateResult, context) =>
123 context.client.invalidateQueries({ queryKey: ['todos'] }),
124})
125```
126​
127[//]: # 'Example'
128​
129### Updating a single todo
130​
131[//]: # 'Example2'
132​
133```tsx
134useMutation({
135 mutationFn: updateTodo,
136 // When mutate is called:
137 onMutate: async (newTodo, context) => {
138 // Cancel any outgoing refetches
139 // (so they don't overwrite our optimistic update)
140 await context.client.cancelQueries({ queryKey: ['todos', newTodo.id] })
141​
142 // Snapshot the previous value
143 const previousTodo = context.client.getQueryData(['todos', newTodo.id])
144​
145 // Optimistically update to the new value
146 context.client.setQueryData(['todos', newTodo.id], newTodo)
147​
148 // Return a result with the previous and new todo
149 return { previousTodo, newTodo }
150 },
151 // If the mutation fails, use the result we returned above
152 onError: (err, newTodo, onMutateResult, context) => {
153 context.client.setQueryData(
154 ['todos', onMutateResult.newTodo.id],
155 onMutateResult.previousTodo,
156 )
157 },
158 // Always refetch after error or success:
159 onSettled: (newTodo, error, variables, onMutateResult, context) =>
160 context.client.invalidateQueries({ queryKey: ['todos', newTodo.id] }),
161})
162```
163​
164[//]: # 'Example2'
165​
166You can also use the `onSettled` function in place of the separate `onError` and `onSuccess` handlers if you wish:
167​
168[//]: # 'Example3'
169​
170```tsx
171useMutation({
172 mutationFn: updateTodo,
173 // ...
174 onSettled: async (newTodo, error, variables, onMutateResult, context) => {
175 if (error) {
176 // do something
177 }
178 },
179})
180```
181​
182[//]: # 'Example3'
183​
184## When to use what
185​
186If you only have one place where the optimistic result should be shown, using `variables` and updating the UI directly is the approach that requires less code and is generally easier to reason about. For example, you don't need to handle rollbacks at all.
187​
188However, if you have multiple places on the screen that would require to know about the update, manipulating the cache directly will take care of this for you automatically.
189​
190[//]: # 'Materials'
191​
192## Further reading
193​
194Have a look at the guide by TkDodo on [Concurrent Optimistic Updates](https://tkdodo.eu/blog/concurrent-optimistic-updates-in-react-query).
195​
196[//]: # 'Materials'