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