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

createMutation.svelte.ts

244 lines7.2 KB

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