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

mutations.md

270 lines6.1 KB

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