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