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

createMutation.svelte.ts

237 lines7.2 KB

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