Open History to see the last commit
1---
2id: optimistic-updates
3title: Optimistic Updates
4ref: docs/framework/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```angular-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```angular-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β
75mutationState = injectMutationState<string>(() => ({
76 filters: { mutationKey: ['addTodo'], status: 'pending' },
77 select: (mutation) => mutation.state.variables,
78}))
79```
80β
81[//]: # 'ExampleUI4'
82[//]: # 'Example'
83β
84```ts
85queryClient = inject(QueryClient)
86β
87updateTodo = injectMutation(() => ({
88 mutationFn: updateTodo,
89 // When mutate is called:
90 onMutate: async (newTodo, context) => {
91 // Cancel any outgoing refetches
92 // (so they don't overwrite our optimistic update)
93 await context.client.cancelQueries({ queryKey: ['todos'] })
94β
95 // Snapshot the previous value
96 const previousTodos = context.client.getQueryData(['todos'])
97β
98 // Optimistically update to the new value
99 context.client.setQueryData(['todos'], (old) => [...old, newTodo])
100β
101 // Return a result object with the snapshotted value
102 return { previousTodos }
103 },
104 // If the mutation fails,
105 // use the result returned from onMutate to roll back
106 onError: (err, newTodo, onMutateResult, context) => {
107 context.client.setQueryData(['todos'], onMutateResult.previousTodos)
108 },
109 // Always refetch after error or success:
110 onSettled: (data, error, variables, onMutateResult, context) => {
111 context.client.invalidateQueries({ queryKey: ['todos'] })
112 },
113}))
114```
115β
116[//]: # 'Example'
117[//]: # 'Example2'
118β
119```ts
120queryClient = inject(QueryClient)
121β
122updateTodo = injectMutation(() => ({
123 mutationFn: updateTodo,
124 // When mutate is called:
125 onMutate: async (newTodo, context) => {
126 // Cancel any outgoing refetches
127 // (so they don't overwrite our optimistic update)
128 await context.client.cancelQueries({ queryKey: ['todos', newTodo.id] })
129β
130 // Snapshot the previous value
131 const previousTodo = context.client.getQueryData(['todos', newTodo.id])
132β
133 // Optimistically update to the new value
134 context.client.setQueryData(['todos', newTodo.id], newTodo)
135β
136 // Return a result with the previous and new todo
137 return { previousTodo, newTodo }
138 },
139 // If the mutation fails, use the result we returned above
140 onError: (err, newTodo, onMutateResult, context) => {
141 context.client.setQueryData(
142 ['todos', onMutateResult.newTodo.id],
143 onMutateResult.previousTodo,
144 )
145 },
146 // Always refetch after error or success:
147 onSettled: (newTodo, error, variables, onMutateResult, context) => {
148 context.client.invalidateQueries({ queryKey: ['todos', newTodo.id] })
149 },
150}))
151```
152β
153[//]: # 'Example2'
154[//]: # 'Example3'
155β
156```ts
157injectMutation({
158 mutationFn: updateTodo,
159 // ...
160 onSettled: (newTodo, error, variables, onMutateResult, context) => {
161 if (error) {
162 // do something
163 }
164 },
165})
166```
167β
168[//]: # 'Example3'