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