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

optimistic-updates.md

192 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 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: async () => {
20 return await queryClient.invalidateQueries({ queryKey: ['todos'] })
21 },
22})
23​
24const { isPending, submittedAt, variables, mutate, isError } = addTodoMutation
25```
26​
27[//]: # 'ExampleUI1'
28​
29you 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`:
30​
31[//]: # 'ExampleUI2'
32​
33```tsx
34<ul>
35 {todoQuery.items.map((todo) => (
36 <li key={todo.id}>{todo.text}</li>
37 ))}
38 {isPending && <li style={{ opacity: 0.5 }}>{variables}</li>}
39</ul>
40```
41​
42[//]: # 'ExampleUI2'
43​
44We'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.
45​
46If 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:
47​
48[//]: # 'ExampleUI3'
49​
50```tsx
52 isError && (
53 <li style={{ color: 'red' }}>
54 {variables}
55 <button onClick={() => mutate(variables)}>Retry</button>
56 </li>
57 )
59```
60​
61[//]: # 'ExampleUI3'
62​
63### If the mutation and the query don't live in the same component
64​
65This 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`:
66​
67[//]: # 'ExampleUI4'
68​
69```tsx
70// somewhere in your app
71const { mutate } = useMutation({
72 mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
73 onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
74 mutationKey: ['addTodo'],
75})
76​
77// access variables somewhere else
78const variables = useMutationState<string>({
79 filters: { mutationKey: ['addTodo'], status: 'pending' },
80 select: (mutation) => mutation.state.variables,
81})
82```
83​
84[//]: # 'ExampleUI4'
85​
86`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.
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 roll back 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​
130[//]: # 'Example'
131​
132### Updating a single todo
133​
134[//]: # 'Example2'
135​
136```tsx
137useMutation({
138 mutationFn: updateTodo,
139 // When mutate is called:
140 onMutate: async (newTodo) => {
141 // Cancel any outgoing refetches
142 // (so they don't overwrite our optimistic update)
143 await queryClient.cancelQueries({ queryKey: ['todos', newTodo.id] })
144​
145 // Snapshot the previous value
146 const previousTodo = queryClient.getQueryData(['todos', newTodo.id])
147​
148 // Optimistically update to the new value
149 queryClient.setQueryData(['todos', newTodo.id], newTodo)
150​
151 // Return a context with the previous and new todo
152 return { previousTodo, newTodo }
153 },
154 // If the mutation fails, use the context we returned above
155 onError: (err, newTodo, context) => {
156 queryClient.setQueryData(
157 ['todos', context.newTodo.id],
158 context.previousTodo,
159 )
160 },
161 // Always refetch after error or success:
162 onSettled: (newTodo) => {
163 queryClient.invalidateQueries({ queryKey: ['todos', newTodo.id] })
164 },
165})
166```
167​
168[//]: # 'Example2'
169​
170You can also use the `onSettled` function in place of the separate `onError` and `onSuccess` handlers if you wish:
171​
172[//]: # 'Example3'
173​
174```tsx
175useMutation({
176 mutationFn: updateTodo,
177 // ...
178 onSettled: (newTodo, error, variables, context) => {
179 if (error) {
180 // do something
181 }
182 },
183})
184```
185​
186[//]: # 'Example3'
187​
188## When to use what
189​
190If 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.
191​
192However, 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.