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

createMutation.md

215 lines6.2 KB

1---
2id: createMutation
3title: createMutation
4---
5​
6<!-- DO NOT EDIT: this page is autogenerated from the type comments -->
7​
8```ts
9function createMutation<TData = unknown, TError = Error, TVariables = void, TContext = unknown>(options: Accessor<CreateMutationOptions<TData, TError, TVariables, TContext>>, queryClient?: Accessor<QueryClient>): CreateMutationResult<TData, TError, TVariables, TContext>;
10```
11​
12Defined in: [packages/svelte-query/src/createMutation.svelte.ts:165](https://github.com/TanStack/query/blob/main/packages/svelte-query/src/createMutation.svelte.ts#L165)
13​
14Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
15`createMutation` is the function for that.
16​
17## Type Parameters
18​
19### TData
20​
21`TData` = `unknown`
22​
23### TError
24​
25`TError` = `Error`
26​
27### TVariables
28​
29`TVariables` = `void`
30​
31### TContext
32​
33`TContext` = `unknown`
34​
35## Parameters
36​
37### options
38​
39[`Accessor`](../type-aliases/Accessor.md)\<[`CreateMutationOptions`](../type-aliases/CreateMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TContext`\>\>
40​
41The [CreateMutationOptions](../type-aliases/CreateMutationOptions.md) to use, wrapped in an [Accessor](../type-aliases/Accessor.md) so options can be
42reactive.
43​
44<a id="options-properties"></a>
45​
46#### `options` properties
47​
48Built from [`MutationObserverOptions`](../interfaces/MutationObserverOptions.md#properties). See the type above for what it changes.
49​
50### queryClient?
51​
52[`Accessor`](../type-aliases/Accessor.md)\<[`QueryClient`](../classes/QueryClient.md)\>
53​
54Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
55be used.
56​
57## Returns
58​
59[`CreateMutationResult`](../type-aliases/CreateMutationResult.md)\<`TData`, `TError`, `TVariables`, `TContext`\>
60​
61`mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second
62argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared
63mutation definition. If you make multiple requests, `onSuccess` will fire only after the latest call you've
64made.
65​
66<a id="result-properties"></a>
67​
68### Result properties
69​
70Built from [`MutationObserverBaseResult`](../interfaces/MutationObserverBaseResult.md#properties). See the type above for what it changes.
71​
72## See
73​
74[mutationOptions](mutationOptions.md) to share these options across multiple `createMutation` call sites, or to look
75the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`).
76​
77## Examples
78​
79```svelte
80<script lang="ts">
81 import { createMutation, useQueryClient } from '@tanstack/svelte-query'
82​
83 const queryClient = useQueryClient()
84​
85 const addMutation = createMutation(() => ({
86 mutationFn: addTodo,
87 onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
88 }))
89</script>
90​
91<button
92 onclick={() =>
93 addMutation.mutate('Item', {
94 onError: (error) => console.error('Failed to add item:', error),
95 })
96 }
98 Add
99</button>
100```
101​
102Rendering the mutation's own state, rather than just firing it off:
103```svelte
104<script lang="ts">
105 import { createMutation, useQueryClient } from '@tanstack/svelte-query'
106​
107 const queryClient = useQueryClient()
108​
109 const addMutation = createMutation(() => ({
110 mutationFn: addTodo,
111 onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
112 }))
113</script>
114​
115{#if addMutation.isPending}
116 Adding todo...
117{:else}
118 {#if addMutation.isError}
119 <div>An error occurred: {addMutation.error.message}</div>
120 {/if}
121 <button onclick={() => addMutation.mutate('Item')}>Add</button>
122{/if}
123```
124​
125Optimistic update via `onMutate`, rolling back on `onError`:
126```svelte
127<script lang="ts">
128 import { createMutation, useQueryClient } from '@tanstack/svelte-query'
129​
130 const queryClient = useQueryClient()
131​
132 const addMutation = createMutation(() => ({
133 mutationFn: addTodo,
134 onMutate: async (newTodo: string) => {
135 await queryClient.cancelQueries({ queryKey: ['todos'] })
136 const previousTodos = queryClient.getQueryData<Array<string>>(['todos'])
137​
138 queryClient.setQueryData<Array<string>>(['todos'], (old) => [
139 ...(old ?? []),
140 newTodo,
141 ])
142​
143 // Passed to `onError` as `onMutateResult` if the mutation fails.
144 return { previousTodos }
145 },
146 onError: (_err, _newTodo, onMutateResult) => {
147 queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
148 },
149 onSettled: () => {
150 queryClient.invalidateQueries({ queryKey: ['todos'] })
151 },
152 }))
153</script>
154​
155<button onclick={() => addMutation.mutate('Item')}>Add</button>
156```
157​
158Callbacks passed per call to `mutate` only fire for the last call β€” `mutateAsync` gives you a
159promise per call instead, so you can wait for all of them when they succeed:
160```svelte
161<script lang="ts">
162 import { createMutation, useQueryClient } from '@tanstack/svelte-query'
163​
164 const queryClient = useQueryClient()
165​
166 const addMutation = createMutation(() => ({
167 mutationFn: addTodo,
168 onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
169 }))
170​
171 async function handleAddAll(todos: Array<string>) {
172 try {
173 await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo)))
174 } catch (error) {
175 console.error('Failed to add todos:', error)
176 }
177 }
178</script>
179​
180<button onclick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
181 Add all
182</button>
183```
184​
185If some of the mutations above can fail independently of the others, and you want to know which ones
186did β€” rather than losing that information the moment the first one rejects β€” swap `Promise.all` for
187`Promise.allSettled`:
188```svelte
189<script lang="ts">
190 import { createMutation, useQueryClient } from '@tanstack/svelte-query'
191​
192 const queryClient = useQueryClient()
193​
194 const addMutation = createMutation(() => ({
195 mutationFn: addTodo,
196 onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
197 }))
198​
199 async function handleAddAll(todos: Array<string>) {
200 const addResults = await Promise.allSettled(
201 todos.map((todo) => addMutation.mutateAsync(todo)),
202 )
203​
204 addResults.forEach((addResult, index) => {
205 if (addResult.status === 'rejected') {
206 console.error(`Failed to add "${todos[index]}":`, addResult.reason)
207 }
208 })
209 }
210</script>
211​
212<button onclick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
213 Add all
214</button>
215```