Open History to see the last commit
1---
2id: optimistic-updates
3title: Optimistic Updates
4---
5β
6When 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.
7β
8To 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.
9β
10## Updating a list of todos when adding a new todo
11β
12[//]: # 'Example'
13β
14```tsx
15const queryClient = useQueryClient()
16β
17useMutation({
18 mutationFn: updateTodo,
19 // When mutate is called:
20 onMutate: async (newTodo) => {
21 // Cancel any outgoing refetches
22 // (so they don't overwrite our optimistic update)
23 await queryClient.cancelQueries({ queryKey: ['todos'] })
24β
25 // Snapshot the previous value
26 const previousTodos = queryClient.getQueryData(['todos'])
27β
28 // Optimistically update to the new value
29 queryClient.setQueryData(['todos'], (old) => [...old, newTodo])
30β
31 // Return a context object with the snapshotted value
32 return { previousTodos }
33 },
34 // If the mutation fails,
35 // use the context returned from onMutate to roll back
36 onError: (err, newTodo, context) => {
37 queryClient.setQueryData(['todos'], context.previousTodos)
38 },
39 // Always refetch after error or success:
40 onSettled: () => {
41 queryClient.invalidateQueries({ queryKey: ['todos'] })
42 },
43})
44```
45β
46[//]: # 'Example'
47β
48## Updating a single todo
49β
50[//]: # 'Example2'
51β
52```tsx
53useMutation({
54 mutationFn: updateTodo,
55 // When mutate is called:
56 onMutate: async (newTodo) => {
57 // Cancel any outgoing refetches
58 // (so they don't overwrite our optimistic update)
59 await queryClient.cancelQueries({ queryKey: ['todos', newTodo.id] })
60β
61 // Snapshot the previous value
62 const previousTodo = queryClient.getQueryData(['todos', newTodo.id])
63β
64 // Optimistically update to the new value
65 queryClient.setQueryData(['todos', newTodo.id], newTodo)
66β
67 // Return a context with the previous and new todo
68 return { previousTodo, newTodo }
69 },
70 // If the mutation fails, use the context we returned above
71 onError: (err, newTodo, context) => {
72 queryClient.setQueryData(
73 ['todos', context.newTodo.id],
74 context.previousTodo,
75 )
76 },
77 // Always refetch after error or success:
78 onSettled: (newTodo) => {
79 queryClient.invalidateQueries({ queryKey: ['todos', newTodo.id] })
80 },
81})
82```
83β
84[//]: # 'Example2'
85β
86You can also use the `onSettled` function in place of the separate `onError` and `onSuccess` handlers if you wish:
87β
88[//]: # 'Example3'
89β
90```tsx
91useMutation({
92 mutationFn: updateTodo,
93 // ...
94 onSettled: (newTodo, error, variables, context) => {
95 if (error) {
96 // do something
97 }
98 },
99})
100```
101β
102[//]: # 'Example3'