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 => axios.post('/todos', newTodo))
13β
14 return (
15 <div>
16 {mutation.isLoading ? (
17 'Adding todo...'
18 ) : (
19 <>
20 {mutation.isError ? (
21 <div>An error occurred: {mutation.error.message}</div>
22 ) : null}
23β
24 {mutation.isSuccess ? <div>Todo added!</div> : null}
25β
26 <button
27 onClick={() => {
28 mutation.mutate({ id: new Date(), title: 'Do Laundry' })
29 }}
30 >
31 Create Todo
32 </button>
33 </>
34 )}
35 </div>
36 )
37}
38```
39β
40A mutation can only be in one of the following states at any given moment:
41β
42- `isIdle` or `status === 'idle'` - The mutation is currently idle or in a fresh/reset state
43- `isLoading` or `status === 'loading'` - The mutation is currently running
44- `isError` or `status === 'error'` - The mutation encountered an error
45- `isSuccess` or `status === 'success'` - The mutation was successful and mutation data is available
46β
47Beyond those primary states, more information is available depending on the state of the mutation:
48β
49- `error` - If the mutation is in an `error` state, the error is available via the `error` property.
50- `data` - If the mutation is in a `success` state, the data is available via the `data` property.
51β
52In 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**.
53β
54Even 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.
55β
56> 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).
57β
58```js
59// This will not work in React 16 and earlier
60const CreateTodo = () => {
61 const mutation = useMutation(event => {
62 event.preventDefault()
63 return fetch('/api', new FormData(event.target))
64 })
65β
66 return <form onSubmit={mutation.mutate}>...</form>
67}
68β
69// This will work
70const CreateTodo = () => {
71 const mutation = useMutation(formData => {
72 return fetch('/api', formData)
73 })
74 const onSubmit = event => {
75 event.preventDefault()
76 mutation.mutate(new FormData(event.target))
77 }
78β
79 return <form onSubmit={onSubmit}>...</form>
80}
81```
82β
83## Resetting Mutation State
84β
85It'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:
86β
87```js
88const CreateTodo = () => {
89 const [title, setTitle] = useState('')
90 const mutation = useMutation(createTodo)
91β
92 const onCreateTodo = e => {
93 e.preventDefault()
94 mutation.mutate({ title })
95 }
96β
97 return (
98 <form onSubmit={onCreateTodo}>
99 {mutation.error && (
100 <h5 onClick={() => mutation.reset()}>{mutation.error}</h5>
101 )}
102 <input
103 type="text"
104 value={title}
105 onChange={e => setTitle(e.target.value)}
106 />
107 <br />
108 <button type="submit">Create Todo</button>
109 </form>
110 )
111}
112```
113β
114## Mutation Side Effects
115β
116`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)
117β
118```js
119useMutation(addTodo, {
120 onMutate: variables => {
121 // A mutation is about to happen!
122β
123 // Optionally return a context containing data to use when for example rolling back
124 return { id: 1 }
125 },
126 onError: (error, variables, context) => {
127 // An error happened!
128 console.log(`rolling back optimistic update with id ${context.id}`)
129 },
130 onSuccess: (data, variables, context) => {
131 // Boom baby!
132 },
133 onSettled: (data, error, variables, context) => {
134 // Error or success... doesn't matter!
135 },
136})
137```
138β
139When returning a promise in any of the callback functions it will first be awaited before the next callback is called:
140β
141```js
142useMutation(addTodo, {
143 onSuccess: async () => {
144 console.log("I'm first!")
145 },
146 onSettled: async () => {
147 console.log("I'm second!")
148 },
149})
150```
151β
152You 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.
153β
154```js
155useMutation(addTodo, {
156 onSuccess: (data, variables, context) => {
157 // I will fire first
158 },
159 onError: (error, variables, context) => {
160 // I will fire first
161 },
162 onSettled: (data, error, variables, context) => {
163 // I will fire first
164 },
165})
166β
167mutate(todo, {
168 onSuccess: (data, variables, context) => {
169 // I will fire second!
170 },
171 onError: (error, variables, context) => {
172 // I will fire second!
173 },
174 onSettled: (data, error, variables, context) => {
175 // I will fire second!
176 },
177})
178```
179β
180## Promises
181β
182Use `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.
183β
184```js
185const mutation = useMutation(addTodo)
186β
187try {
188 const todo = await mutation.mutateAsync(todo)
189 console.log(todo)
190} catch (error) {
191 console.error(error)
192} finally {
193 console.log('done')
194}
195```
196β
197## Retry
198β
199By default React Query will not retry a mutation on error, but it is possible with the `retry` option:
200β
201```js
202const mutation = useMutation(addTodo, {
203 retry: 3,
204})
205```
206β
207If mutations fail because the device is offline, they will be retried in the same order when the device reconnects.
208β
209## Persist mutations
210β
211Mutations can be persisted to storage if needed and resumed at a later point. This can be done with the hydration functions:
212β
213```js
214const queryClient = new QueryClient()
215β
216// Define the "addTodo" mutation
217queryClient.setMutationDefaults('addTodo', {
218 mutationFn: addTodo,
219 onMutate: async (variables) => {
220 // Cancel current queries for the todos list
221 await queryClient.cancelQueries('todos')
222β
223 // Create optimistic todo
224 const optimisticTodo = { id: uuid(), title: variables.title }
225β
226 // Add optimistic todo to todos list
227 queryClient.setQueryData('todos', old => [...old, optimisticTodo])
228β
229 // Return context with the optimistic todo
230 return { optimisticTodo }
231 },
232 onSuccess: (result, variables, context) => {
233 // Replace optimistic todo in the todos list with the result
234 queryClient.setQueryData('todos', old => old.map(todo => todo.id === context.optimisticTodo.id ? result : todo))
235 },
236 onError: (error, variables, context) => {
237 // Remove optimistic todo from the todos list
238 queryClient.setQueryData('todos', old => old.filter(todo => todo.id !== context.optimisticTodo.id))
239 },
240 retry: 3,
241})
242β
243// Start mutation in some component:
244const mutation = useMutation('addTodo')
245mutation.mutate({ title: 'title' })
246β
247// If the mutation has been paused because the device is for example offline,
248// Then the paused mutation can be dehydrated when the application quits:
249const state = dehydrate(queryClient)
250β
251// The mutation can then be hydrated again when the application is started:
252hydrate(queryClient, state)
253β
254// Resume the paused mutations:
255queryClient.resumePausedMutations()
256```