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

optimistic-updates.md

188 lines6.7 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```tsx
14 const { isPending, submittedAt, variables, mutate, isError } = useMutation({
15 mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
16 // make sure to _return_ the Promise from the query invalidation
17 // so that the mutation stays in `pending` state until the refetch is finished
18 onSettled: async () => {
19 return await queryClient.invalidateQueries({ queryKey: ['todos'] })
20 },
21 })
22```
23[//]: # 'ExampleUI1'
24​
25you 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`:
26​
27[//]: # 'ExampleUI2'
28```tsx
29<ul>
30 {todoQuery.items.map((todo) => (
31 <li key={todo.id}>{todo.text}</li>
32 ))}
33 {isPending && (
34 <li
35 key={String(submittedAt)}
36 style={{ opacity: 0.5 }}
37 >
38 {variables}
39 </li>
40 )}
41</ul>
42```
43[//]: # 'ExampleUI2'
44​
45The `submittedAt` property is a timestamp that is set when `mutate` is invoked. This is useful to create a unique key for the pending todo item. We've also added an `opacity` to indicate that this item is only temporarily here. Once the mutation completes, the item will be removed because the mutation is no longer `pending`. Given that the refetch succeeded, we should see the item as a "normal item" in our list.
46​
47If 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:
48​
49[//]: # 'ExampleUI3'
50```tsx
51{isError && (
52 <li
53 key={String(submittedAt)}
54 style={{ color: 'red' }}
55 >
56 {variables}
57 <button onClick={() => mutate(variables)}>
58 Retry
59 </button>
60 </li>
61)}
62```
63[//]: # 'ExampleUI3'
64​
65### If the mutation and the query don't live in the same component
66​
67This 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`:
68​
69[//]: # 'ExampleUI4'
70```tsx
71// somewhere in your app
72const { mutate } = useMutation({
73 mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
74 onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
75 mutationKey: ['addTodo']
76})
77​
78// access variables somewhere else
79const variables = useMutationState<string>({
80 filters: { mutationKey: ['addTodo'], status: 'pending' },
81 select: (mutation) => mutation.state.variables
82})
83```
84[//]: # 'ExampleUI4'
85​
86`variables` will be an `Array`, because there might be multiple mutations running at the same time. This will even make displaying concurrent optimistic updates a breeze.
87​
88## Via the cache
89​
90When 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 rollback your update.
91​
92To 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.
93​
94### Updating a list of todos when adding a new todo
95​
96[//]: # 'Example'
97​
98```tsx
99const queryClient = useQueryClient()
100​
101useMutation({
102 mutationFn: updateTodo,
103 // When mutate is called:
104 onMutate: async (newTodo) => {
105 // Cancel any outgoing refetches
106 // (so they don't overwrite our optimistic update)
107 await queryClient.cancelQueries({ queryKey: ['todos'] })
108​
109 // Snapshot the previous value
110 const previousTodos = queryClient.getQueryData(['todos'])
111​
112 // Optimistically update to the new value
113 queryClient.setQueryData(['todos'], (old) => [...old, newTodo])
114​
115 // Return a context object with the snapshotted value
116 return { previousTodos }
117 },
118 // If the mutation fails,
119 // use the context returned from onMutate to roll back
120 onError: (err, newTodo, context) => {
121 queryClient.setQueryData(['todos'], context.previousTodos)
122 },
123 // Always refetch after error or success:
124 onSettled: () => {
125 queryClient.invalidateQueries({ queryKey: ['todos'] })
126 },
127})
128```
129[//]: # 'Example'
130​
131### Updating a single todo
132​
133[//]: # 'Example2'
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[//]: # 'Example2'
166​
167You can also use the `onSettled` function in place of the separate `onError` and `onSuccess` handlers if you wish:
168​
169[//]: # 'Example3'
170```tsx
171useMutation({
172 mutationFn: updateTodo,
173 // ...
174 onSettled: (newTodo, error, variables, context) => {
175 if (error) {
176 // do something
177 }
178 },
179})
180```
181[//]: # 'Example3'
182​
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.