Open History to see the last commit
1---
2id: mutations
3title: Mutations
4ref: docs/framework/react/guides/mutations.md
5replace: { 'hook': 'primitive' }
6---
7β
8[//]: # 'Example'
9β
10```tsx
11import { Switch, Match, Show } from 'solid-js'
12β
13function App() {
14 const mutation = useMutation(() => ({
15 mutationFn: (newTodo) => {
16 return axios.post('/todos', newTodo)
17 },
18 }))
19β
20 return (
21 <div>
22 <Switch>
23 <Match when={mutation.isPending}>Adding todo...</Match>
24 <Match when={true}>
25 <Show when={mutation.isError}>
26 <div>An error occurred: {mutation.error.message}</div>
27 </Show>
28β
29 <Show when={mutation.isSuccess}>
30 <div>Todo added!</div>
31 </Show>
32β
33 <button
34 onClick={() => {
35 mutation.mutate({ id: new Date(), title: 'Do Laundry' })
36 }}
37 >
38 Create Todo
39 </button>
40 </Match>
41 </Switch>
42 </div>
43 )
44}
45```
46β
47[//]: # 'Example'
48[//]: # 'Info1'
49[//]: # 'Info1'
50[//]: # 'Example2'
51β
52```tsx
53const CreateTodo = () => {
54 const mutation = useMutation(() => ({
55 mutationFn: (formData) => {
56 return fetch('/api', formData)
57 },
58 }))
59 const onSubmit = (event) => {
60 event.preventDefault()
61 mutation.mutate(new FormData(event.target))
62 }
63β
64 return <form onSubmit={onSubmit}>...</form>
65}
66```
67β
68[//]: # 'Example2'
69[//]: # 'Example3'
70β
71```tsx
72import { createSignal, Show } from 'solid-js'
73β
74const CreateTodo = () => {
75 const [title, setTitle] = createSignal('')
76 const mutation = useMutation(() => ({ mutationFn: createTodo }))
77β
78 const onCreateTodo = (e) => {
79 e.preventDefault()
80 mutation.mutate({ title: title() })
81 }
82β
83 return (
84 <form onSubmit={onCreateTodo}>
85 <Show when={mutation.error}>
86 <h5 onClick={() => mutation.reset()}>{mutation.error}</h5>
87 </Show>
88 <input
89 type="text"
90 value={title()}
91 onInput={(e) => setTitle(e.currentTarget.value)}
92 />
93 <br />
94 <button type="submit">Create Todo</button>
95 </form>
96 )
97}
98```
99β
100[//]: # 'Example3'
101[//]: # 'Example4'
102β
103```tsx
104useMutation(() => ({
105 mutationFn: addTodo,
106 onMutate: (variables, context) => {
107 // A mutation is about to happen!
108β
109 // Optionally return a result containing data to use when for example rolling back
110 return { id: 1 }
111 },
112 onError: (error, variables, onMutateResult, context) => {
113 // An error happened!
114 console.log(`rolling back optimistic update with id ${onMutateResult.id}`)
115 },
116 onSuccess: (data, variables, onMutateResult, context) => {
117 // Boom baby!
118 },
119 onSettled: (data, error, variables, onMutateResult, context) => {
120 // Error or success... doesn't matter!
121 },
122}))
123```
124β
125[//]: # 'Example4'
126[//]: # 'Example5'
127β
128```tsx
129useMutation(() => ({
130 mutationFn: addTodo,
131 onSuccess: async () => {
132 console.log("I'm first!")
133 },
134 onSettled: async () => {
135 console.log("I'm second!")
136 },
137}))
138```
139β
140[//]: # 'Example5'
141[//]: # 'Example6'
142β
143```tsx
144useMutation(() => ({
145 mutationFn: addTodo,
146 onSuccess: (data, variables, onMutateResult, context) => {
147 // I will fire first
148 },
149 onError: (error, variables, onMutateResult, context) => {
150 // I will fire first
151 },
152 onSettled: (data, error, variables, onMutateResult, context) => {
153 // I will fire first
154 },
155}))
156β
157mutate(todo, {
158 onSuccess: (data, variables, onMutateResult, context) => {
159 // I will fire second!
160 },
161 onError: (error, variables, onMutateResult, context) => {
162 // I will fire second!
163 },
164 onSettled: (data, error, variables, onMutateResult, context) => {
165 // I will fire second!
166 },
167})
168```
169β
170[//]: # 'Example6'
171[//]: # 'Example7'
172β
173```tsx
174useMutation(() => ({
175 mutationFn: addTodo,
176 onSuccess: (data, variables, onMutateResult, context) => {
177 // Will be called 3 times
178 },
179}))
180β
181const todos = ['Todo 1', 'Todo 2', 'Todo 3']
182todos.forEach((todo) => {
183 mutate(todo, {
184 onSuccess: (data, variables, onMutateResult, context) => {
185 // Will execute only once, for the last mutation (Todo 3),
186 // regardless which mutation resolves first
187 },
188 })
189})
190```
191β
192[//]: # 'Example7'
193[//]: # 'Example8'
194β
195```tsx
196const mutation = useMutation(() => ({ mutationFn: addTodo }))
197β
198try {
199 const todo = await mutation.mutateAsync(todo)
200 console.log(todo)
201} catch (error) {
202 console.error(error)
203} finally {
204 console.log('done')
205}
206```
207β
208[//]: # 'Example8'
209[//]: # 'Example9'
210β
211```tsx
212const mutation = useMutation(() => ({
213 mutationFn: addTodo,
214 retry: 3,
215}))
216```
217β
218[//]: # 'Example9'
219[//]: # 'Example10'
220β
221```tsx
222const queryClient = new QueryClient()
223β
224// Define the "addTodo" mutation
225queryClient.setMutationDefaults(['addTodo'], {
226 mutationFn: addTodo,
227 onMutate: async (variables, context) => {
228 // Cancel current queries for the todos list
229 await context.client.cancelQueries({ queryKey: ['todos'] })
230β
231 // Create optimistic todo
232 const optimisticTodo = { id: uuid(), title: variables.title }
233β
234 // Add optimistic todo to todos list
235 context.client.setQueryData(['todos'], (old) => [...old, optimisticTodo])
236β
237 // Return a result with the optimistic todo
238 return { optimisticTodo }
239 },
240 onSuccess: (result, variables, onMutateResult, context) => {
241 // Replace optimistic todo in the todos list with the result
242 context.client.setQueryData(['todos'], (old) =>
243 old.map((todo) =>
244 todo.id === onMutateResult.optimisticTodo.id ? result : todo,
245 ),
246 )
247 },
248 onError: (error, variables, onMutateResult, context) => {
249 // Remove optimistic todo from the todos list
250 context.client.setQueryData(['todos'], (old) =>
251 old.filter((todo) => todo.id !== onMutateResult.optimisticTodo.id),
252 )
253 },
254 retry: 3,
255})
256β
257// Start mutation in some component:
258const mutation = useMutation(() => ({ mutationKey: ['addTodo'] }))
259mutation.mutate({ title: 'title' })
260β
261// If the mutation has been paused because the device is for example offline,
262// Then the paused mutation can be dehydrated when the application quits:
263const state = dehydrate(queryClient)
264β
265// The mutation can then be hydrated again when the application is started:
266hydrate(queryClient, state)
267β
268// Resume the paused mutations:
269queryClient.resumePausedMutations()
270```
271β
272[//]: # 'Example10'
273[//]: # 'PersistOfflineIntro'
274β
275### Persisting Offline mutations
276β
277If you persist offline mutations with the `persistQueryClient` plugin, mutations cannot be resumed when the page is reloaded unless you provide a default mutation function.
278β
279[//]: # 'PersistOfflineIntro'
280[//]: # 'OfflineExampleLink'
281[//]: # 'OfflineExampleLink'
282[//]: # 'ExampleScopes'
283β
284```tsx
285const mutation = useMutation(() => ({
286 mutationFn: addTodo,
287 scope: {
288 id: 'todo',
289 },
290}))
291```
292β
293[//]: # 'ExampleScopes'
294[//]: # 'Materials'
295β
296## Further reading
297β
298For more information about mutations, have a look at [TkDodo's article on Mastering Mutations in TanStack Query](https://tkdodo.eu/blog/mastering-mutations-in-react-query).
299β
300[//]: # 'Materials'