Open History to see the last commit
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 )
43}
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>
82}
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>
97}
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 )
132}
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')
263}
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 )
387}
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'