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```js
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```js
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```js
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](./invalidations-from-mutations) and even [optimistic updates](./optimistic-updates)
119β
120```js
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```js
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** than 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```js
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## Promises
183β
184Use `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.
185β
186```js
187const mutation = useMutation(addTodo)
188β
189try {
190 const todo = await mutation.mutateAsync(todo)
191 console.log(todo)
192} catch (error) {
193 console.error(error)
194} finally {
195 console.log('done')
196}
197```
198β
199## Retry
200β
201By default React Query will not retry a mutation on error, but it is possible with the `retry` option:
202β
203```js
204const mutation = useMutation(addTodo, {
205 retry: 3,
206})
207```
208β
209If mutations fail because the device is offline, they will be retried in the same order when the device reconnects.
210β
211## Persist mutations
212β
213Mutations can be persisted to storage if needed and resumed at a later point. This can be done with the hydration functions:
214β
215```js
216const queryClient = new QueryClient()
217β
218// Define the "addTodo" mutation
219queryClient.setMutationDefaults('addTodo', {
220 mutationFn: addTodo,
221 onMutate: async (variables) => {
222 // Cancel current queries for the todos list
223 await queryClient.cancelQueries('todos')
224β
225 // Create optimistic todo
226 const optimisticTodo = { id: uuid(), title: variables.title }
227β
228 // Add optimistic todo to todos list
229 queryClient.setQueryData('todos', old => [...old, optimisticTodo])
230β
231 // Return context with the optimistic todo
232 return { optimisticTodo }
233 },
234 onSuccess: (result, variables, context) => {
235 // Replace optimistic todo in the todos list with the result
236 queryClient.setQueryData('todos', old => old.map(todo => todo.id === context.optimisticTodo.id ? result : todo))
237 },
238 onError: (error, variables, context) => {
239 // Remove optimistic todo from the todos list
240 queryClient.setQueryData('todos', old => old.filter(todo => todo.id !== context.optimisticTodo.id))
241 },
242 retry: 3,
243})
244β
245// Start mutation in some component:
246const mutation = useMutation('addTodo')
247mutation.mutate({ title: 'title' })
248β
249// If the mutation has been paused because the device is for example offline,
250// Then the paused mutation can be dehydrated when the application quits:
251const state = dehydrate(queryClient)
252β
253// The mutation can then be hydrated again when the application is started:
254hydrate(queryClient, state)
255β
256// Resume the paused mutations:
257queryClient.resumePausedMutations()
258```
259β
260## Further reading
261β
262For more information about mutations, have a look at [#12: Mastering Mutations in React Query](../community/tkdodos-blog#12-mastering-mutations-in-react-query) from
263the Community Resources.