Open History to see the last commit
1import { noop, shouldThrowError } from '@tanstack/query-core'
2import {
3 action,
4 createMemo,
5 createOptimistic,
6 createRenderEffect,
7 createSignal,
8 onCleanup,
9 untrack,
10} from 'solid-js'
11import { useQueryClient } from './QueryClientProvider'
12import type {
13 DefaultError,
14 Mutation,
15 MutationFunctionContext,
16} from '@tanstack/query-core'
17import type { QueryClient } from './QueryClient'
18import type {
19 UseMutateFunction,
20 UseMutationOptions,
21 UseMutationResult,
22} from './types'
23import type { Accessor } from 'solid-js'
24β
25const isServer = typeof window === 'undefined'
26β
27/**
28 * Durable mutation state: written post-`yield` inside the action's
29 * transaction, so it commits atomically with everything else the settle
30 * carries (invalidation-triggered refetches included).
31 */
32interface SettledState<TData, TError, TVariables> {
33 status: 'idle' | 'success' | 'error'
34 data: TData | undefined
35 error: TError | null
36 variables: TVariables | undefined
37 submittedAt: number
38}
39β
40const IDLE: SettledState<any, any, any> = {
41 status: 'idle',
42 data: undefined,
43 error: null,
44 variables: undefined,
45 submittedAt: 0,
46}
47β
48/**
49 * Drive the mutation generator without transaction semantics β the server
50 * has no interactive paint to keep atomic. Yielded thenable values are
51 * awaited and their results passed back in, matching what `action` does
52 * minus the transition bookkeeping.
53 * @param iterator - The mutation generator to run to completion.
54 * @returns A promise for the generator's return value.
55 */
56async function drain<TReturn>(
57 iterator: AsyncGenerator<unknown, TReturn, unknown>,
58): Promise<TReturn> {
59 let input: unknown
60 for (;;) {
61 const result = await iterator.next(input)
62 if (result.done) return result.value
63 input = result.value != null ? await result.value : undefined
64 }
65}
66β
67/**
68 * Mutations ride core `action`: each `mutate()` call is one transaction.
69 *
70 * - Transient flight state (`isPending`, in-flight `variables`) is a
71 * `createOptimistic` overlay written at the top of the action β visible
72 * immediately, dropped automatically when the transition settles. The
73 * engine's revert-on-settle IS the submission state machine.
74 * - `options.onMutate(variables)` runs inside the same window: it is the
75 * place to apply the caller's own optimistic overlays
76 * (`createOptimistic` / `createOptimisticStore` writes). No context
77 * object, no rollback plumbing β reverting is the engine's job.
78 * - The fetch itself goes through query-core:
79 * `mutationCache.build().execute()` supplies retry/backoff, offline
80 * pausing, scoped serial execution, and cache-level lifecycle callbacks.
81 * No `MutationObserver` β the adapter reads the Mutation's state
82 * directly where flight metadata (failureCount, isPaused) is needed.
83 * - Options-level callbacks are stripped from the built mutation and
84 * re-run *post-`yield`*, inside the transaction: an
85 * `onSuccess β invalidateQueries` chain issues version bumps whose
86 * refetches hold this very transition, so mutation success and fresh
87 * query data land in one atomic paint (and a single-flight payload has
88 * already primed the cache by the time `execute` resolves).
89 * - One `mutate`, returning a safe-to-ignore promise: rejection is also
90 * routed into reactive state, and a no-op catch keeps the ignored
91 * branch from surfacing as an unhandled rejection. The
92 * `mutate`/`mutateAsync` split existed for React's callback-vs-promise
93 * error routing; it has no space here.
94 * @param options - An accessor returning the {@link UseMutationOptions} to use.
95 * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
96 * will be used.
97 * @returns The mutation state, with `mutate` to run the mutation and `reset` to clear its state.
98 */
99export function useMutation<
100 TData = unknown,
101 TError = DefaultError,
102 TVariables = void,
103 TOnMutateResult = unknown,
104>(
105 options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,
106 queryClient?: Accessor<QueryClient>,
107): UseMutationResult<TData, TError, TVariables, TOnMutateResult> {
108 const client = createMemo(() => useQueryClient(queryClient?.()))
109β
110 /** Optimistic overlay: non-null exactly while a mutation is in flight. */
111 const [flight, setFlight] = createOptimistic<{
112 variables: TVariables
113 } | null>(null)
114β
115 const [settled, setSettled] = createSignal<
116 SettledState<TData, TError, TVariables>
117 >(IDLE as SettledState<TData, TError, TVariables>)
118β
119 /**
120 * Flight metadata (retry failures, offline pause) lives on the Mutation
121 * instance and changes during the await gap; a version bump per cache
122 * event for the active mutation keeps reads current without cloning
123 * observer results. The subscription is per-flight, created in `run`
124 * against the same client the mutation is built on: nothing reactive is
125 * read at setup (no client read to untrack), the listener and the
126 * mutation can never sit on different clients, and an idle hook holds no
127 * cache subscription at all.
128 */
129 let activeMutation: Mutation<TData, TError, TVariables> | null = null
130 let unsubscribeFlight: (() => void) | null = null
131 const [flightVersion, setFlightVersion] = createSignal(0)
132 if (!isServer)
133 onCleanup(() => {
134 unsubscribeFlight?.()
135 unsubscribeFlight = null
136 })
137β
138 /**
139 * Runs one mutation: the flight overlay and `onMutate`, the fetch through query-core, then the
140 * options-level callbacks and the durable settle.
141 * @param variables - The variables passed to `mutate`.
142 * @returns The data the mutation resolved with.
143 * @yields {unknown} The promises the surrounding `action` (or `drain` on the server) awaits.
144 */
145 async function* run(
146 variables: TVariables,
147 ): AsyncGenerator<unknown, TData, unknown> {
148 const opts = untrack(options)
149 const callbackContext: MutationFunctionContext = {
150 client: untrack(client),
151 meta: opts.meta,
152 mutationKey: opts.mutationKey,
153 }
154 // Server render is pure (rc.3 deprecates server setter calls): the
155 // drain path only needs the return value/throw, so all reactive
156 // bookkeeping β flight overlay and durable settle β is client-only.
157 if (!isServer) setFlight({ variables })
158 opts.onMutate?.(variables, callbackContext)
159β
160 const c = untrack(client)
161 const mutation = c.getMutationCache().build(c, {
162 ...opts,
163 // Options-level callbacks re-run below, inside the transaction β
164 // executing them here (inside the await gap) would let their
165 // cache writes and invalidations escape the atomic settle.
166 onMutate: undefined,
167 onSuccess: undefined,
168 onError: undefined,
169 onSettled: undefined,
170 })
171 activeMutation = mutation
172 if (!isServer) {
173 // A rapid re-mutate replaces the previous flight's listener.
174 unsubscribeFlight?.()
175 unsubscribeFlight = c.getMutationCache().subscribe((event) => {
176 if ('mutation' in event && event.mutation === activeMutation) {
177 setFlightVersion((v) => v + 1)
178 }
179 })
180 }
181 const settleFlight = () => {
182 if (activeMutation !== mutation) return
183 activeMutation = null
184 unsubscribeFlight?.()
185 unsubscribeFlight = null
186 }
187β
188 /**
189 * Failure settle, shared by both paths. Callback routing mirrors
190 * query-core's `Mutation.execute` (which never sees these callbacks β
191 * they are stripped from the built mutation and re-run here, inside
192 * the transaction): `onError` and an error-shaped `onSettled` run,
193 * their own failures are reported as unhandled rejections but never
194 * displace `error`, then the durable error state commits and the
195 * mutate promise rejects with `error`.
196 * @param error - The error the mutation or one of its success callbacks failed with.
197 * @yields {unknown} The promises returned by `onError` and `onSettled`.
198 */
199 // Must be an async generator: async `yield` awaits its value in place,
200 // so a rejecting callback promise throws at the yield inside the local
201 // try/catch. A sync generator delegated from an async one gets its
202 // values unwrapped by the async-from-sync adapter *outside* the inner
203 // frame β the rejection would bypass these catches and kill the run.
204 // eslint-disable-next-line @typescript-eslint/require-await -- async for yield-await semantics, not await expressions
205 async function* settleFailure(
206 error: TError,
207 ): AsyncGenerator<unknown, never, unknown> {
208 try {
209 if (opts.onError)
210 yield opts.onError(error, variables, undefined, callbackContext)
211 } catch (callbackError) {
212 void Promise.reject(callbackError)
213 }
214 try {
215 if (opts.onSettled)
216 yield opts.onSettled(
217 undefined,
218 error,
219 variables,
220 undefined,
221 callbackContext,
222 )
223 } catch (callbackError) {
224 void Promise.reject(callbackError)
225 }
226 if (!isServer)
227 setSettled({
228 status: 'error',
229 data: undefined,
230 error,
231 variables,
232 submittedAt: mutation.state.submittedAt,
233 })
234 settleFlight()
235 throw error
236 }
237β
238 let result: TData
239 try {
240 result = await mutation.execute(variables)
241 } catch (error) {
242 yield // re-enter the transaction before writing
243 yield* settleFailure(error as TError)
244 // Unreachable β settleFailure always throws. Explicit for TS's
245 // definite-assignment analysis of `result` (yield* delegation is
246 // not narrowed as never-returning).
247 throw error
248 }
249 yield // re-enter the transaction before writing
250 try {
251 if (opts.onSuccess)
252 yield opts.onSuccess(
253 result,
254 variables,
255 undefined as TOnMutateResult,
256 callbackContext,
257 )
258 if (opts.onSettled)
259 yield opts.onSettled(
260 result,
261 null,
262 variables,
263 undefined,
264 callbackContext,
265 )
266 } catch (callbackError) {
267 // Mirror core: a success-path callback failure fails the mutation β
268 // even though the cache entry committed success, the hook settles
269 // to error with the callback error, and awaiting mutate rejects.
270 yield* settleFailure(callbackError as TError)
271 // Unreachable β settleFailure always throws (see above).
272 throw callbackError
273 }
274 if (!isServer)
275 setSettled({
276 status: 'success',
277 data: result,
278 error: null,
279 variables,
280 submittedAt: mutation.state.submittedAt,
281 })
282 settleFlight()
283 return result
284 }
285β
286 const invoke: (variables: TVariables) => Promise<TData> = isServer
287 ? (variables) => drain(run(variables))
288 : action(run)
289β
290 const mutate: UseMutateFunction<
291 TData,
292 TError,
293 TVariables,
294 TOnMutateResult
295 > = (...args) => {
296 const promise = invoke(args[0] as TVariables)
297 // Errors also land in reactive state; ignoring the promise must not
298 // surface an unhandled rejection. Awaiting it still rejects.
299 promise.catch(noop)
300 return promise
301 }
302β
303 const status = () => (flight() !== null ? 'pending' : settled().status)
304 const isPending = () => flight() !== null
305β
306 /**
307 * Errors surface to `<Errored>` when `throwOnError` opts in. The throw
308 * must happen in the compute half so it routes through notifyStatus and
309 * boundary accounting.
310 */
311 createRenderEffect(
312 () => {
313 const state = settled()
314 if (
315 state.status === 'error' &&
316 shouldThrowError(untrack(options).throwOnError, [state.error as TError])
317 ) {
318 throw state.error
319 }
320 },
321 () => {},
322 )
323β
324 const result = {
325 mutate,
326 get data() {
327 return settled().data
328 },
329 get error() {
330 return flight() !== null ? null : settled().error
331 },
332 get variables() {
333 return flight()?.variables ?? settled().variables
334 },
335 get status() {
336 return status()
337 },
338 get isPending() {
339 return isPending()
340 },
341 get isIdle() {
342 return status() === 'idle'
343 },
344 get isSuccess() {
345 return status() === 'success'
346 },
347 get isError() {
348 return status() === 'error'
349 },
350 get submittedAt() {
351 return flight() !== null
352 ? (flightVersion(), activeMutation?.state.submittedAt ?? 0)
353 : settled().submittedAt
354 },
355 get failureCount() {
356 flightVersion()
357 return activeMutation?.state.failureCount ?? 0
358 },
359 get failureReason() {
360 flightVersion()
361 return (activeMutation?.state.failureReason ?? null) as TError | null
362 },
363 get isPaused() {
364 flightVersion()
365 return activeMutation?.state.isPaused ?? false
366 },
367 reset: () => {
368 setSettled(IDLE as SettledState<TData, TError, TVariables>)
369 },
370 }
371β
372 return result
373}