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

createMutation.md

213 lines6.1 KB

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 }
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```