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

optimistic-updates.md

84 lines2.8 KB

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```tsx
13const queryClient = useQueryClient()
14​
15useMutation(updateTodo, {
16 // When mutate is called:
17 onMutate: async newTodo => {
18 // Cancel any outgoing refetches (so they don't overwrite our optimistic update)
19 await queryClient.cancelQueries(['todos'])
20​
21 // Snapshot the previous value
22 const previousTodos = queryClient.getQueryData(['todos'])
23​
24 // Optimistically update to the new value
25 queryClient.setQueryData(['todos'], old => [...old, newTodo])
26​
27 // Return a context object with the snapshotted value
28 return { previousTodos }
29 },
30 // If the mutation fails, use the context returned from onMutate to roll back
31 onError: (err, newTodo, context) => {
32 queryClient.setQueryData(['todos'], context.previousTodos)
33 },
34 // Always refetch after error or success:
35 onSettled: () => {
36 queryClient.invalidateQueries(['todos'])
37 },
38})
39```
40​
41## Updating a single todo
42​
43```tsx
44useMutation(updateTodo, {
45 // When mutate is called:
46 onMutate: async newTodo => {
47 // Cancel any outgoing refetches (so they don't overwrite our optimistic update)
48 await queryClient.cancelQueries(['todos', newTodo.id])
49​
50 // Snapshot the previous value
51 const previousTodo = queryClient.getQueryData(['todos', newTodo.id])
52​
53 // Optimistically update to the new value
54 queryClient.setQueryData(['todos', newTodo.id], newTodo)
55​
56 // Return a context with the previous and new todo
57 return { previousTodo, newTodo }
58 },
59 // If the mutation fails, use the context we returned above
60 onError: (err, newTodo, context) => {
61 queryClient.setQueryData(
62 ['todos', context.newTodo.id],
63 context.previousTodo
64 )
65 },
66 // Always refetch after error or success:
67 onSettled: newTodo => {
68 queryClient.invalidateQueries(['todos', newTodo.id])
69 },
70})
71```
72​
73You can also use the `onSettled` function in place of the separate `onError` and `onSuccess` handlers if you wish:
74​
75```tsx
76useMutation(updateTodo, {
77 // ...
78 onSettled: (newTodo, error, variables, context) => {
79 if (error) {
80 // do something
81 }
82 },
83})
84```