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