Open History to see the last commit
1---
2id: mutations
3title: Mutations
4ref: docs/framework/react/guides/mutations.md
5replace:
6 {
7 'useMutation': 'injectMutation',
8 'hook': 'function',
9 'still mounted': 'still active',
10 'unmounts': 'gets destroyed',
11 'mounted': 'initialized',
12 }
13---
14
15[//]: # 'Example'
16
17```angular-ts
18@Component({
19 template: `
20 <div>
21 @if (createTodoMutation.isPending()) {
22 <span>Adding todo...</span>
23 } @else if (createTodoMutation.isError()) {
24 <div>An error occurred: {{ createTodoMutation.error()?.message }}</div>
25 } @else if (createTodoMutation.isSuccess()) {
26 <div>Todo added!</div>
27 }
28 <button (click)="createTodoMutation.mutate(1)">Create Todo</button>
29 </div>
30 `,
31})
32export class TodosComponent {
33 readonly todoService = inject(TodoService)
34 readonly createTodoMutation = injectMutation(() => ({
35 mutationFn: (todoId: number) =>
36 lastValueFrom(this.todoService.create(todoId)),
37 }))
38}
39```
40
41[//]: # 'Example'
42[//]: # 'Info1'
43[//]: # 'Info1'
44[//]: # 'Example2'
45[//]: # 'Example2'
46[//]: # 'Example3'
47
48```angular-ts
49@Component({
50 selector: 'todo-item',
51 imports: [ReactiveFormsModule],
52 template: `
53 <form [formGroup]="todoForm" (ngSubmit)="onCreateTodo()">
54 @if (createTodoMutation.error()) {
55 <h5 (click)="createTodoMutation.reset()">
56 {{ createTodoMutation.error() }}
57 </h5>
58 }
59 <input type="text" formControlName="title" />
60 <br />
61 <button type="submit">Create Todo</button>
62 </form>
63 `,
64})
65export class TodosComponent {
66 readonly createTodoMutation = injectMutation(() => ({
67 mutationFn: createTodo,
68 }))
69
70 readonly fb = inject(NonNullableFormBuilder)
71
72 todoForm = this.fb.group({
73 title: this.fb.control('', {
74 validators: [Validators.required],
75 }),
76 })
77
78 title = toSignal(this.todoForm.controls.title.valueChanges, {
79 initialValue: '',
80 })
81
82 onCreateTodo = () => {
83 this.createTodoMutation.mutate(this.title())
84 }
85}
86```
87
88[//]: # 'Example3'
89[//]: # 'Example4'
90
91```ts
92addTodoMutation = injectMutation(() => ({
93 mutationFn: addTodo,
94 onMutate: (variables, context) => {
95 // A mutation is about to happen!
96
97 // Optionally return a result containing data to use when for example rolling back
98 return { id: 1 }
99 },
100 onError: (error, variables, onMutateResult, context) => {
101 // An error happened!
102 console.log(`rolling back optimistic update with id ${onMutateResult.id}`)
103 },
104 onSuccess: (data, variables, onMutateResult, context) => {
105 // Boom baby!
106 },
107 onSettled: (data, error, variables, onMutateResult, context) => {
108 // Error or success... doesn't matter!
109 },
110}))
111```
112
113[//]: # 'Example4'
114[//]: # 'Example5'
115
116```ts
117addTodoMutation = injectMutation(() => ({
118 mutationFn: addTodo,
119 onSuccess: async () => {
120 console.log("I'm first!")
121 },
122 onSettled: async () => {
123 console.log("I'm second!")
124 },
125}))
126```
127
128[//]: # 'Example5'
129[//]: # 'Example6'
130
131```ts
132addTodoMutation = injectMutation(() => ({
133 mutationFn: addTodo,
134 onSuccess: (data, variables, onMutateResult, context) => {
135 // I will fire first
136 },
137 onError: (error, variables, onMutateResult, context) => {
138 // I will fire first
139 },
140 onSettled: (data, error, variables, onMutateResult, context) => {
141 // I will fire first
142 },
143}))
144
145addTodoMutation.mutate(todo, {
146 onSuccess: (data, variables, onMutateResult, context) => {
147 // I will fire second!
148 },
149 onError: (error, variables, onMutateResult, context) => {
150 // I will fire second!
151 },
152 onSettled: (data, error, variables, onMutateResult, context) => {
153 // I will fire second!
154 },
155})
156```
157
158[//]: # 'Example6'
159[//]: # 'Example7'
160
161```ts
162export class Example {
163 readonly addTodoMutation = injectMutation(() => ({
164 mutationFn: addTodo,
165 onSuccess: (data, variables, onMutateResult, context) => {
166 // Will be called 3 times
167 },
168 }))
169
170 doMutations() {
171 ;['Todo 1', 'Todo 2', 'Todo 3'].forEach((todo) => {
172 this.addTodoMutation.mutate(todo, {
173 onSuccess: (data, variables, onMutateResult, context) => {
174 // Will execute only once, for the last mutation (Todo 3),
175 // regardless which mutation resolves first
176 },
177 })
178 })
179 }
180}
181```
182
183[//]: # 'Example7'
184[//]: # 'Example8'
185
186```ts
187addTodoMutation = injectMutation(() => ({ mutationFn: addTodo }))
188
189try {
190 const todo = await addTodoMutation.mutateAsync(todo)
191 console.log(todo)
192} catch (error) {
193 console.error(error)
194} finally {
195 console.log('done')
196}
197```
198
199[//]: # 'Example8'
200[//]: # 'Example9'
201
202```ts
203addTodoMutation = injectMutation(() => ({
204 mutationFn: addTodo,
205 retry: 3,
206}))
207```
208
209[//]: # 'Example9'
210[//]: # 'Example10'
211
212```ts
213const queryClient = new QueryClient()
214
215// Define the "addTodo" mutation
216queryClient.setMutationDefaults(['addTodo'], {
217 mutationFn: addTodo,
218 onMutate: async (variables, context) => {
219 // Cancel current queries for the todos list
220 await context.client.cancelQueries({ queryKey: ['todos'] })
221
222 // Create optimistic todo
223 const optimisticTodo = { id: uuid(), title: variables.title }
224
225 // Add optimistic todo to todos list
226 context.client.setQueryData(['todos'], (old) => [...old, optimisticTodo])
227
228 // Return result with the optimistic todo
229 return { optimisticTodo }
230 },
231 onSuccess: (result, variables, onMutateResult, context) => {
232 // Replace optimistic todo in the todos list with the result
233 context.client.setQueryData(['todos'], (old) =>
234 old.map((todo) =>
235 todo.id === onMutateResult.optimisticTodo.id ? result : todo,
236 ),
237 )
238 },
239 onError: (error, variables, onMutateResult, context) => {
240 // Remove optimistic todo from the todos list
241 context.client.setQueryData(['todos'], (old) =>
242 old.filter((todo) => todo.id !== onMutateResult.optimisticTodo.id),
243 )
244 },
245 retry: 3,
246})
247
248class someComponent {
249 // Start mutation in some component:
250 readonly addTodoMutation = injectMutation(() => ({
251 mutationKey: ['addTodo'],
252 }))
253
254 someMethod() {
255 addTodoMutation.mutate({ title: 'title' })
256 }
257}
258
259// If the mutation has been paused because the device is for example offline,
260// Then the paused mutation can be dehydrated when the application quits:
261const state = dehydrate(queryClient)
262
263// The mutation can then be hydrated again when the application is started:
264hydrate(queryClient, state)
265
266// Resume the paused mutations:
267queryClient.resumePausedMutations()
268```
269
270[//]: # 'Example10'
271[//]: # 'Example11'
272[//]: # 'Example11'
273[//]: # 'OfflineExampleLink'
274[//]: # 'OfflineExampleLink'
275[//]: # 'Materials'
276[//]: # 'Materials'
277
278See [Error handling](./error-handling.md) to connect cache failures to Angular’s `ErrorHandler`.