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, React Query exports a `useMutation` hook.
7β
8Here's an example of a mutation that adds a new todo to the server:
9β
10```tsx
11function App() {
12 const mutation = useMutation(newTodo => {
13 return axios.post('/todos', newTodo)
14 })
15β
16 return (
17 <div>
18 {mutation.isLoading ? (
19 'Adding todo...'
20 ) : (
21 <>
22 {mutation.isError ? (
23 <div>An error occurred: {mutation.error.message}</div>
24 ) : null}
25β
26 {mutation.isSuccess ? <div>Todo added!</div> : null}
27β
28 <button
29 onClick={() => {
30 mutation.mutate({ id: new Date(), title: 'Do Laundry' })
31 }}
32 >
33 Create Todo
34 </button>
35 </>
36 )}
37 </div>
38 )
39}
40```
41β
42A mutation can only be in one of the following states at any given moment:
43β
44- `isIdle` or `status === 'idle'` - The mutation is currently idle or in a fresh/reset state
45- `isLoading` or `status === 'loading'` - The mutation is currently running
46- `isError` or `status === 'error'` - The mutation encountered an error
47- `isSuccess` or `status === 'success'` - The mutation was successful and mutation data is available
48β
49Beyond those primary states, more information is available depending on the state of the mutation:
50β
51- `error` - If the mutation is in an `error` state, the error is available via the `error` property.
52- `data` - If the mutation is in a `success` state, the data is available via the `data` property.
53β
54In 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**.
55β
56Even with just variables, mutations aren't all that special, but when used with the `onSuccess` option, the [Query Client's `invalidateQueries` method](../reference/QueryClient#queryclientinvalidatequeries) and the [Query Client's `setQueryData` method](../reference/QueryClient#queryclientsetquerydata), mutations become a very powerful tool.
57β
58> 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).
59β
60```tsx
61// This will not work in React 16 and earlier
62const CreateTodo = () => {
63 const mutation = useMutation(event => {
64 event.preventDefault()
65 return fetch('/api', new FormData(event.target))
66 })
67β
68 return <form onSubmit={mutation.mutate}>...</form>
69}
70β
71// This will work
72const CreateTodo = () => {
73 const mutation = useMutation(formData => {
74 return fetch('/api', formData)
75 })
76 const onSubmit = event => {
77 event.preventDefault()
78 mutation.mutate(new FormData(event.target))
79 }
80β
81 return <form onSubmit={onSubmit}>...</form>
82}
83```
84β
85## Resetting Mutation State
86β
87It'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:
88β
89```tsx
90const CreateTodo = () => {
91 const [title, setTitle] = useState('')
92 const mutation = useMutation(createTodo)
93β
94 const onCreateTodo = e => {
95 e.preventDefault()
96 mutation.mutate({ title })
97 }
98β
99 return (
100 <form onSubmit={onCreateTodo}>
101 {mutation.error && (
102 <h5 onClick={() => mutation.reset()}>{mutation.error}</h5>
103 )}
104 <input
105 type="text"
106 value={title}
107 onChange={e => setTitle(e.target.value)}
108 />
109 <br />
110 <button type="submit">Create Todo</button>
111 </form>
112 )
113}
114```
115β
116## Mutation Side Effects
117β
118`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](../guides/invalidations-from-mutations) and even [optimistic updates](../guides/optimistic-updates)
119β
120```tsx
121useMutation(addTodo, {
122 onMutate: variables => {
123 // A mutation is about to happen!
124β
125 // Optionally return a context containing data to use when for example rolling back
126 return { id: 1 }
127 },
128 onError: (error, variables, context) => {
129 // An error happened!
130 console.log(`rolling back optimistic update with id ${context.id}`)
131 },
132 onSuccess: (data, variables, context) => {
133 // Boom baby!
134 },
135 onSettled: (data, error, variables, context) => {
136 // Error or success... doesn't matter!
137 },
138})
139```
140β
141When returning a promise in any of the callback functions it will first be awaited before the next callback is called:
142β
143```tsx
144useMutation(addTodo, {
145 onSuccess: async () => {
146 console.log("I'm first!")
147 },
148 onSettled: async () => {
149 console.log("I'm second!")
150 },
151})
152```
153β
154You 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 overrides include: `onSuccess`, `onError` and `onSettled`. Please keep in mind that those additional callbacks won't run if your component unmounts _before_ the mutation finishes.
155β
156```tsx
157useMutation(addTodo, {
158 onSuccess: (data, variables, context) => {
159 // I will fire first
160 },
161 onError: (error, variables, context) => {
162 // I will fire first
163 },
164 onSettled: (data, error, variables, context) => {
165 // I will fire first
166 },
167})
168β
169mutate(todo, {
170 onSuccess: (data, variables, context) => {
171 // I will fire second!
172 },
173 onError: (error, variables, context) => {
174 // I will fire second!
175 },
176 onSettled: (data, error, variables, context) => {
177 // I will fire second!
178 },
179})
180```
181β
182### Consecutive mutations
183There 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.
184β
185> 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.
186β
187```tsx
188useMutation(addTodo, {
189 onSuccess: (data, error, variables, context) => {
190 // Will be called 3 times
191 },
192})
193β
194['Todo 1', 'Todo 2', 'Todo 3'].forEach((todo) => {
195 mutate(todo, {
196 onSuccess: (data, error, variables, context) => {
197 // Will execute only once, for the last mutation (Todo 3),
198 // regardless which mutation resolves first
199 },
200 })
201})
202β
203```
204## Promises
205β
206Use `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.
207β
208```tsx
209const mutation = useMutation(addTodo)
210β
211try {
212 const todo = await mutation.mutateAsync(todo)
213 console.log(todo)
214} catch (error) {
215 console.error(error)
216} finally {
217 console.log('done')
218}
219```
220β
221## Retry
222β
223By default React Query will not retry a mutation on error, but it is possible with the `retry` option:
224β
225```tsx
226const mutation = useMutation(addTodo, {
227 retry: 3,
228})
229```
230β
231If mutations fail because the device is offline, they will be retried in the same order when the device reconnects.
232β
233## Persist mutations
234β
235Mutations can be persisted to storage if needed and resumed at a later point. This can be done with the hydration functions:
236β
237```tsx
238const queryClient = new QueryClient()
239β
240// Define the "addTodo" mutation
241queryClient.setMutationDefaults(['addTodo'], {
242 mutationFn: addTodo,
243 onMutate: async (variables) => {
244 // Cancel current queries for the todos list
245 await queryClient.cancelQueries(['todos'])
246β
247 // Create optimistic todo
248 const optimisticTodo = { id: uuid(), title: variables.title }
249β
250 // Add optimistic todo to todos list
251 queryClient.setQueryData(['todos'], old => [...old, optimisticTodo])
252β
253 // Return context with the optimistic todo
254 return { optimisticTodo }
255 },
256 onSuccess: (result, variables, context) => {
257 // Replace optimistic todo in the todos list with the result
258 queryClient.setQueryData(['todos'], old => old.map(todo => todo.id === context.optimisticTodo.id ? result : todo))
259 },
260 onError: (error, variables, context) => {
261 // Remove optimistic todo from the todos list
262 queryClient.setQueryData(['todos'], old => old.filter(todo => todo.id !== context.optimisticTodo.id))
263 },
264 retry: 3,
265})
266β
267// Start mutation in some component:
268const mutation = useMutation(['addTodo'])
269mutation.mutate({ title: 'title' })
270β
271// If the mutation has been paused because the device is for example offline,
272// Then the paused mutation can be dehydrated when the application quits:
273const state = dehydrate(queryClient)
274β
275// The mutation can then be hydrated again when the application is started:
276hydrate(queryClient, state)
277β
278// Resume the paused mutations:
279queryClient.resumePausedMutations()
280```
281β
282### Persisting Offline mutations
283β
284If you persist offline mutations with the [persistQueryClient plugin](../plugins/persistQueryClient), mutations cannot be resumed when the page is reloaded unless you provide a default mutation function.
285β
286This 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 triggeres the mutation might not be mounted, so calling `resumePausedMutations` might yield an error: `No mutationFn found`.
287β
288```tsx
289const persister = createSyncStoragePersister({
290 storage: window.localStorage,
291})
292const queryClient = new QueryClient({
293 defaultOptions: {
294 queries: {
295 cacheTime: 1000 * 60 * 60 * 24, // 24 hours
296 },
297 },
298})
299β
300// we need a default mutation function so that paused mutations can resume after a page reload
301queryClient.setMutationDefaults(['todos'], {
302 mutationFn: ({ id, data }) => {
303 return api.updateTodo(id, data)
304 },
305})
306β
307export default function App() {
308 return (
309 <PersistQueryClientProvider
310 client={queryClient}
311 persistOptions={{ persister }}
312 onSuccess={() => {
313 // resume mutations after initial restore from localStorage was successful
314 queryClient.resumePausedMutations()
315 }}
316 >
317 <RestOfTheApp />
318 </PersistQueryClientProvider>
319 )
320}
321```
322β
323We also have an extensive [offline example](../examples/react/offline) that covers both queries and mutations.
324β
325## Further reading
326β
327For more information about mutations, have a look at [#12: Mastering Mutations in React Query](../community/tkdodos-blog#12-mastering-mutations-in-react-query) from
328the Community Resources.