Open History to see the last commit
1---
2id: optimistic-updates
3title: Optimistic Updates
4ref: docs/react/guides/optimistic-updates.md
5replace:
6 {
7 'React': 'Angular',
8 'useMutation': 'injectMutation',
9 'hook': 'function',
10 'useMutationState': 'injectMutationState',
11 'addTodoMutation': 'addTodo',
12 }
13---
14β
15[//]: # 'ExampleUI1'
16β
17```ts
18addTodo = injectMutation(() => ({
19 mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
20 // make sure to _return_ the Promise from the query invalidation
21 // so that the mutation stays in `pending` state until the refetch is finished
22 onSettled: async () => {
23 return await queryClient.invalidateQueries({ queryKey: ['todos'] })
24 },
25}))
26```
27β
28[//]: # 'ExampleUI1'
29[//]: # 'ExampleUI2'
30β
31```ts
32@Component({
33 template: `
34 @for (todo of todos.data(); track todo.id) {
35 <li>{{ todo.title }}</li>
36 }
37 @if (addTodo.isPending()) {
38 <li style="opacity: 0.5">{{ addTodo.variables() }}</li>
39 }
40 `,
41})
42class TodosComponent {}
43```
44β
45[//]: # 'ExampleUI2'
46[//]: # 'ExampleUI3'
47β
48```ts
49@Component({
50 template: `
51 @if (addTodo.isError()) {
52 <li style="color: red">
53 {{ addTodo.variables() }}
54 <button (click)="addTodo.mutate(addTodo.variables())">Retry</button>
55 </li>
56 }
57 `,
58})
59class TodosComponent {}
60```
61β
62[//]: # 'ExampleUI3'
63[//]: # 'ExampleUI4'
64β
65```ts
66// somewhere in your app
67addTodo = injectMutation(() => ({
68 mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
69 onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
70 mutationKey: ['addTodo'],
71}))
72β
73// access variables somewhere else
74β
75// Note: injectMutationState is not available yet in Angular Query
76mutationState = injectMutationState<string>(() => ({
77 filters: { mutationKey: ['addTodo'], status: 'pending' },
78 select: (mutation) => mutation.state.variables,
79}))
80```
81β
82[//]: # 'ExampleUI4'
83[//]: # 'Example'
84β
85```ts
86updateTodo = injectMutation((client) => ({
87 mutationFn: updateTodo,
88 // When mutate is called:
89 onMutate: async (newTodo) => {
90 // Cancel any outgoing refetches
91 // (so they don't overwrite our optimistic update)
92 await client.cancelQueries({ queryKey: ['todos'] })
93β
94 // Snapshot the previous value
95 const previousTodos = client.getQueryData(['todos'])
96β
97 // Optimistically update to the new value
98 client.setQueryData(['todos'], (old) => [...old, newTodo])
99β
100 // Return a context object with the snapshotted value
101 return { previousTodos }
102 },
103 // If the mutation fails,
104 // use the context returned from onMutate to roll back
105 onError: (err, newTodo, context) => {
106 client.setQueryData(['todos'], context.previousTodos)
107 },
108 // Always refetch after error or success:
109 onSettled: () => {
110 client.invalidateQueries({ queryKey: ['todos'] })
111 },
112}))
113```
114β
115[//]: # 'Example'
116[//]: # 'Example2'
117β
118```ts
119updateTodo = injectMutation((client) => ({
120 mutationFn: updateTodo,
121 // When mutate is called:
122 onMutate: async (newTodo) => {
123 // Cancel any outgoing refetches
124 // (so they don't overwrite our optimistic update)
125 await client.cancelQueries({ queryKey: ['todos', newTodo.id] })
126β
127 // Snapshot the previous value
128 const previousTodo = client.getQueryData(['todos', newTodo.id])
129β
130 // Optimistically update to the new value
131 client.setQueryData(['todos', newTodo.id], newTodo)
132β
133 // Return a context with the previous and new todo
134 return { previousTodo, newTodo }
135 },
136 // If the mutation fails, use the context we returned above
137 onError: (err, newTodo, context) => {
138 client.setQueryData(['todos', context.newTodo.id], context.previousTodo)
139 },
140 // Always refetch after error or success:
141 onSettled: (newTodo) => {
142 client.invalidateQueries({ queryKey: ['todos', newTodo.id] })
143 },
144}))
145```
146β
147[//]: # 'Example2'
148[//]: # 'Example3'
149β
150```ts
151injectMutation({
152 mutationFn: updateTodo,
153 // ...
154 onSettled: (newTodo, error, variables, context) => {
155 if (error) {
156 // do something
157 }
158 },
159})
160```
161β
162[//]: # 'Example3'