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

mutations.md

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