Open History to see the last commit
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 }
97>
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```