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

optimistic-updates.md

161 lines3.9 KB

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
85updateTodo = injectMutation((client) => ({
86 mutationFn: updateTodo,
87 // When mutate is called:
88 onMutate: async (newTodo) => {
89 // Cancel any outgoing refetches
90 // (so they don't overwrite our optimistic update)
91 await client.cancelQueries({ queryKey: ['todos'] })
92​
93 // Snapshot the previous value
94 const previousTodos = client.getQueryData(['todos'])
95​
96 // Optimistically update to the new value
97 client.setQueryData(['todos'], (old) => [...old, newTodo])
98​
99 // Return a context object with the snapshotted value
100 return { previousTodos }
101 },
102 // If the mutation fails,
103 // use the context returned from onMutate to roll back
104 onError: (err, newTodo, context) => {
105 client.setQueryData(['todos'], context.previousTodos)
106 },
107 // Always refetch after error or success:
108 onSettled: () => {
109 client.invalidateQueries({ queryKey: ['todos'] })
110 },
111}))
112```
113​
114[//]: # 'Example'
115[//]: # 'Example2'
116​
117```ts
118updateTodo = injectMutation((client) => ({
119 mutationFn: updateTodo,
120 // When mutate is called:
121 onMutate: async (newTodo) => {
122 // Cancel any outgoing refetches
123 // (so they don't overwrite our optimistic update)
124 await client.cancelQueries({ queryKey: ['todos', newTodo.id] })
125​
126 // Snapshot the previous value
127 const previousTodo = client.getQueryData(['todos', newTodo.id])
128​
129 // Optimistically update to the new value
130 client.setQueryData(['todos', newTodo.id], newTodo)
131​
132 // Return a context with the previous and new todo
133 return { previousTodo, newTodo }
134 },
135 // If the mutation fails, use the context we returned above
136 onError: (err, newTodo, context) => {
137 client.setQueryData(['todos', context.newTodo.id], context.previousTodo)
138 },
139 // Always refetch after error or success:
140 onSettled: (newTodo) => {
141 client.invalidateQueries({ queryKey: ['todos', newTodo.id] })
142 },
143}))
144```
145​
146[//]: # 'Example2'
147[//]: # 'Example3'
148​
149```ts
150injectMutation({
151 mutationFn: updateTodo,
152 // ...
153 onSettled: (newTodo, error, variables, context) => {
154 if (error) {
155 // do something
156 }
157 },
158})
159```
160​
161[//]: # 'Example3'