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

mutations.md

419 lines12.5 KB

1---
2id: mutations
3title: Mutations
4---
5​
6Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, TanStack Query exports a `useMutation` hook.
7​
8Here's an example of a mutation that adds a new todo to the server:
9​
10[//]: # 'Example'
11​
12```tsx
13function App() {
14 const mutation = useMutation({
15 mutationFn: (newTodo) => {
16 return axios.post('/todos', newTodo)
17 },
18 })
19​
20 return (
21 <div>
22 {mutation.isPending ? (
23 'Adding todo...'
24 ) : (
25 <>
26 {mutation.isError ? (
27 <div>An error occurred: {mutation.error.message}</div>
28 ) : null}
29​
30 {mutation.isSuccess ? <div>Todo added!</div> : null}
31​
32 <button
33 onClick={() => {
34 mutation.mutate({ id: new Date(), title: 'Do Laundry' })
35 }}
36 >
37 Create Todo
38 </button>
39 </>
40 )}
41 </div>
42 )
44```
45​
46[//]: # 'Example'
47​
48A mutation can only be in one of the following states at any given moment:
49​
50- `isIdle` or `status === 'idle'` - The mutation is currently idle or in a fresh/reset state
51- `isPending` or `status === 'pending'` - The mutation is currently running
52- `isError` or `status === 'error'` - The mutation encountered an error
53- `isSuccess` or `status === 'success'` - The mutation was successful and mutation data is available
54​
55Beyond those primary states, more information is available depending on the state of the mutation:
56​
57- `error` - If the mutation is in an `error` state, the error is available via the `error` property.
58- `data` - If the mutation is in a `success` state, the data is available via the `data` property.
59​
60In the example above, you also saw that you can pass variables to your mutations function by calling the `mutate` function with a **single variable or object**.
61​
62Even with just variables, mutations aren't all that special, but when used with the `onSuccess` option, the [Query Client's `invalidateQueries` method](../reference/classes/QueryClient.md#invalidatequeries) and the [Query Client's `setQueryData` method](../reference/classes/QueryClient.md#setquerydata), mutations become a very powerful tool.
63​
64[//]: # 'Info1'
65​
66> IMPORTANT: The `mutate` function is an asynchronous function, which means you cannot use it directly in an event callback in **React 16 and earlier**. If you need to access the event in `onSubmit` you need to wrap `mutate` in another function. This is due to [React event pooling](https://reactjs.org/docs/legacy-event-pooling.html).
67​
68[//]: # 'Info1'
69[//]: # 'Example2'
70​
71```tsx
72// This will not work in React 16 and earlier
73const CreateTodo = () => {
74 const mutation = useMutation({
75 mutationFn: (event) => {
76 event.preventDefault()
77 return fetch('/api', new FormData(event.target))
78 },
79 })
80​
81 return <form onSubmit={mutation.mutate}>...</form>
83​
84// This will work
85const CreateTodo = () => {
86 const mutation = useMutation({
87 mutationFn: (formData) => {
88 return fetch('/api', formData)
89 },
90 })
91 const onSubmit = (event) => {
92 event.preventDefault()
93 mutation.mutate(new FormData(event.target))
94 }
95​
96 return <form onSubmit={onSubmit}>...</form>
98```
99​
100[//]: # 'Example2'
101​
102## Resetting Mutation State
103​
104It's sometimes the case that you need to clear the `error` or `data` of a mutation request. To do this, you can use the `reset` function to handle this:
105​
106[//]: # 'Example3'
107​
108```tsx
109const CreateTodo = () => {
110 const [title, setTitle] = useState('')
111 const mutation = useMutation({ mutationFn: createTodo })
112​
113 const onCreateTodo = (e) => {
114 e.preventDefault()
115 mutation.mutate({ title })
116 }
117​
118 return (
119 <form onSubmit={onCreateTodo}>
120 {mutation.error && (
121 <h5 onClick={() => mutation.reset()}>{mutation.error}</h5>
122 )}
123 <input
124 type="text"
125 value={title}
126 onChange={(e) => setTitle(e.target.value)}
127 />
128 <br />
129 <button type="submit">Create Todo</button>
130 </form>
131 )
133```
134​
135[//]: # 'Example3'
136​
137## Mutation Side Effects
138​
139`useMutation` comes with some helper options that allow quick and easy side-effects at any stage during the mutation lifecycle. These come in handy for both [invalidating and refetching queries after mutations](./invalidations-from-mutations.md) and even [optimistic updates](./optimistic-updates.md)
140​
141[//]: # 'Example4'
142​
143```tsx
144useMutation({
145 mutationFn: addTodo,
146 onMutate: (variables, context) => {
147 // A mutation is about to happen!
148​
149 // Optionally return a result containing data to use when for example rolling back
150 return { id: 1 }
151 },
152 onError: (error, variables, onMutateResult, context) => {
153 // An error happened!
154 console.log(`rolling back optimistic update with id ${onMutateResult.id}`)
155 },
156 onSuccess: (data, variables, onMutateResult, context) => {
157 // Boom baby!
158 },
159 onSettled: (data, error, variables, onMutateResult, context) => {
160 // Error or success... doesn't matter!
161 },
162})
163```
164​
165[//]: # 'Example4'
166​
167When returning a promise in any of the callback functions it will first be awaited before the next callback is called:
168​
169[//]: # 'Example5'
170​
171```tsx
172useMutation({
173 mutationFn: addTodo,
174 onSuccess: async () => {
175 console.log("I'm first!")
176 },
177 onSettled: async () => {
178 console.log("I'm second!")
179 },
180})
181```
182​
183[//]: # 'Example5'
184​
185You might find that you want to **trigger additional callbacks** beyond the ones defined on `useMutation` when calling `mutate`. This can be used to trigger component-specific side effects. To do that, you can provide any of the same callback options to the `mutate` function after your mutation variable. Supported options include: `onSuccess`, `onError` and `onSettled`. Please keep in mind that those additional callbacks won't run if your component unmounts _before_ the mutation finishes.
186​
187[//]: # 'Example6'
188​
189```tsx
190useMutation({
191 mutationFn: addTodo,
192 onSuccess: (data, variables, onMutateResult, context) => {
193 // I will fire first
194 },
195 onError: (error, variables, onMutateResult, context) => {
196 // I will fire first
197 },
198 onSettled: (data, error, variables, onMutateResult, context) => {
199 // I will fire first
200 },
201})
202​
203mutate(todo, {
204 onSuccess: (data, variables, onMutateResult, context) => {
205 // I will fire second!
206 },
207 onError: (error, variables, onMutateResult, context) => {
208 // I will fire second!
209 },
210 onSettled: (data, error, variables, onMutateResult, context) => {
211 // I will fire second!
212 },
213})
214```
215​
216[//]: # 'Example6'
217​
218### Consecutive mutations
219​
220There is a slight difference in handling `onSuccess`, `onError` and `onSettled` callbacks when it comes to consecutive mutations. When passed to the `mutate` function, they will be fired up only _once_ and only if the component is still mounted. This is due to the fact that mutation observer is removed and resubscribed every time when the `mutate` function is called. On the contrary, `useMutation` handlers execute for each `mutate` call.
221​
222> Be aware that most likely, `mutationFn` passed to `useMutation` is asynchronous. In that case, the order in which mutations are fulfilled may differ from the order of `mutate` function calls.
223​
224[//]: # 'Example7'
225​
226```tsx
227useMutation({
228 mutationFn: addTodo,
229 onSuccess: (data, variables, onMutateResult, context) => {
230 // Will be called 3 times
231 },
232})
233​
234const todos = ['Todo 1', 'Todo 2', 'Todo 3']
235todos.forEach((todo) => {
236 mutate(todo, {
237 onSuccess: (data, variables, onMutateResult, context) => {
238 // Will execute only once, for the last mutation (Todo 3),
239 // regardless which mutation resolves first
240 },
241 })
242})
243```
244​
245[//]: # 'Example7'
246​
247## Promises
248​
249Use `mutateAsync` instead of `mutate` to get a promise which will resolve on success or throw on an error. This can for example be used to compose side effects.
250​
251[//]: # 'Example8'
252​
253```tsx
254const mutation = useMutation({ mutationFn: addTodo })
255​
256try {
257 const todo = await mutation.mutateAsync(todo)
258 console.log(todo)
259} catch (error) {
260 console.error(error)
261} finally {
262 console.log('done')
264```
265​
266[//]: # 'Example8'
267​
268## Retry
269​
270By default, TanStack Query will not retry a mutation on error, but it is possible with the `retry` option:
271​
272[//]: # 'Example9'
273​
274```tsx
275const mutation = useMutation({
276 mutationFn: addTodo,
277 retry: 3,
278})
279```
280​
281[//]: # 'Example9'
282​
283If mutations fail because the device is offline, they will be retried in the same order when the device reconnects.
284​
285## Persist mutations
286​
287Mutations can be persisted to storage if needed and resumed at a later point. This can be done with the hydration functions:
288​
289[//]: # 'Example10'
290​
291```tsx
292const queryClient = new QueryClient()
293​
294// Define the "addTodo" mutation
295queryClient.setMutationDefaults(['addTodo'], {
296 mutationFn: addTodo,
297 onMutate: async (variables, context) => {
298 // Cancel current queries for the todos list
299 await context.client.cancelQueries({ queryKey: ['todos'] })
300​
301 // Create optimistic todo
302 const optimisticTodo = { id: uuid(), title: variables.title }
303​
304 // Add optimistic todo to todos list
305 context.client.setQueryData(['todos'], (old) => [...old, optimisticTodo])
306​
307 // Return a result with the optimistic todo
308 return { optimisticTodo }
309 },
310 onSuccess: (result, variables, onMutateResult, context) => {
311 // Replace optimistic todo in the todos list with the result
312 context.client.setQueryData(['todos'], (old) =>
313 old.map((todo) =>
314 todo.id === onMutateResult.optimisticTodo.id ? result : todo,
315 ),
316 )
317 },
318 onError: (error, variables, onMutateResult, context) => {
319 // Remove optimistic todo from the todos list
320 context.client.setQueryData(['todos'], (old) =>
321 old.filter((todo) => todo.id !== onMutateResult.optimisticTodo.id),
322 )
323 },
324 retry: 3,
325})
326​
327// Start mutation in some component:
328const mutation = useMutation({ mutationKey: ['addTodo'] })
329mutation.mutate({ title: 'title' })
330​
331// If the mutation has been paused because the device is for example offline,
332// Then the paused mutation can be dehydrated when the application quits:
333const state = dehydrate(queryClient)
334​
335// The mutation can then be hydrated again when the application is started:
336hydrate(queryClient, state)
337​
338// Resume the paused mutations:
339queryClient.resumePausedMutations()
340```
341​
342[//]: # 'Example10'
343[//]: # 'PersistOfflineIntro'
344​
345### Persisting Offline mutations
346​
347If you persist offline mutations with the [persistQueryClient plugin](../plugins/persistQueryClient.md), mutations cannot be resumed when the page is reloaded unless you provide a default mutation function.
348​
349[//]: # 'PersistOfflineIntro'
350​
351This is a technical limitation. When persisting to an external storage, only the state of mutations is persisted, as functions cannot be serialized. After hydration, the component that triggers the mutation might not be mounted, so calling `resumePausedMutations` might yield an error: `No mutationFn found`.
352​
353[//]: # 'Example11'
354​
355```tsx
356const persister = createAsyncStoragePersister({
357 storage: window.localStorage,
358})
359const queryClient = new QueryClient({
360 defaultOptions: {
361 queries: {
362 gcTime: 24 * 60 * 60 * 1000, // 24 hours
363 },
364 },
365})
366​
367// we need a default mutation function so that paused mutations can resume after a page reload
368queryClient.setMutationDefaults(['todos'], {
369 mutationFn: ({ id, data }) => {
370 return api.updateTodo(id, data)
371 },
372})
373​
374export default function App() {
375 return (
376 <PersistQueryClientProvider
377 client={queryClient}
378 persistOptions={{ persister }}
379 onSuccess={() => {
380 // resume mutations after initial restore from localStorage was successful
381 queryClient.resumePausedMutations()
382 }}
383 >
384 <RestOfTheApp />
385 </PersistQueryClientProvider>
386 )
388```
389​
390[//]: # 'Example11'
391[//]: # 'OfflineExampleLink'
392​
393We also have an extensive [offline example](../examples/offline-tanstack-router) that covers both queries and mutations.
394​
395[//]: # 'OfflineExampleLink'
396​
397## Mutation Scopes
398​
399Per default, all mutations run in parallel - even if you invoke `.mutate()` of the same mutation multiple times. Mutations can be given a `scope` with an `id` to avoid that. All mutations with the same `scope.id` will run in serial, which means when they are triggered, they will start in `isPaused: true` state if there is already a mutation for that scope in progress. They will be put into a queue and will automatically resume once their time in the queue has come.
400​
401[//]: # 'ExampleScopes'
402​
403```tsx
404const mutation = useMutation({
405 mutationFn: addTodo,
406 scope: {
407 id: 'todo',
408 },
409})
410```
411​
412[//]: # 'ExampleScopes'
413[//]: # 'Materials'
414​
415## Further reading
416​
417For more information about mutations, have a look at [TkDodo's article on Mastering Mutations in React Query](https://tkdodo.eu/blog/mastering-mutations-in-react-query).
418​
419[//]: # 'Materials'