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

optimistic-updates.md

190 lines6.5 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 { isPending, submittedAt, variables, mutate, isError } = 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: async () => {
20 return await queryClient.invalidateQueries({ queryKey: ['todos'] })
21 },
22})
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 is `pending`:
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) => {
103 // Cancel any outgoing refetches
104 // (so they don't overwrite our optimistic update)
105 await queryClient.cancelQueries({ queryKey: ['todos'] })
106​
107 // Snapshot the previous value
108 const previousTodos = queryClient.getQueryData(['todos'])
109​
110 // Optimistically update to the new value
111 queryClient.setQueryData(['todos'], (old) => [...old, newTodo])
112​
113 // Return a context object with the snapshotted value
114 return { previousTodos }
115 },
116 // If the mutation fails,
117 // use the context returned from onMutate to roll back
118 onError: (err, newTodo, context) => {
119 queryClient.setQueryData(['todos'], context.previousTodos)
120 },
121 // Always refetch after error or success:
122 onSettled: () => {
123 queryClient.invalidateQueries({ queryKey: ['todos'] })
124 },
125})
126```
127​
128[//]: # 'Example'
129​
130### Updating a single todo
131​
132[//]: # 'Example2'
133​
134```tsx
135useMutation({
136 mutationFn: updateTodo,
137 // When mutate is called:
138 onMutate: async (newTodo) => {
139 // Cancel any outgoing refetches
140 // (so they don't overwrite our optimistic update)
141 await queryClient.cancelQueries({ queryKey: ['todos', newTodo.id] })
142​
143 // Snapshot the previous value
144 const previousTodo = queryClient.getQueryData(['todos', newTodo.id])
145​
146 // Optimistically update to the new value
147 queryClient.setQueryData(['todos', newTodo.id], newTodo)
148​
149 // Return a context with the previous and new todo
150 return { previousTodo, newTodo }
151 },
152 // If the mutation fails, use the context we returned above
153 onError: (err, newTodo, context) => {
154 queryClient.setQueryData(
155 ['todos', context.newTodo.id],
156 context.previousTodo,
157 )
158 },
159 // Always refetch after error or success:
160 onSettled: (newTodo) => {
161 queryClient.invalidateQueries({ queryKey: ['todos', newTodo.id] })
162 },
163})
164```
165​
166[//]: # 'Example2'
167​
168You can also use the `onSettled` function in place of the separate `onError` and `onSuccess` handlers if you wish:
169​
170[//]: # 'Example3'
171​
172```tsx
173useMutation({
174 mutationFn: updateTodo,
175 // ...
176 onSettled: (newTodo, error, variables, context) => {
177 if (error) {
178 // do something
179 }
180 },
181})
182```
183​
184[//]: # 'Example3'
185​
186## When to use what
187​
188If 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.
189​
190However, 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.