Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

mutations.md

267 lines5.8 KB

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