Open History to see the last commit
1// `useMutation` β reimplemented on octane's hooks, mirroring
2// @tanstack/react-query: a MutationObserver subscribed via useSyncExternalStore,
3// with a stable `mutate` callback. The single compiler-injected slot is split
4// into distinct sub-slots for each internal base hook.
5import { useCallback, useEffect, useState, useSyncExternalStore } from 'octane'
6import {
7 MutationObserver,
8 noop,
9 notifyManager,
10 shouldThrowError,
11} from '@tanstack/query-core'
12import { resolveClient } from './context'
13import { splitSlot, subSlot as subSlotBase } from './internal'
14import type { DefaultError, QueryClient } from '@tanstack/query-core'
15import type { UseMutationOptions, UseMutationResult } from './types'
16β
17// Namespaced per-hook (':om:') on top of the shared helper β the minted symbols
18// are byte-identical to the previous private copy, so slot identity is stable.
19const subSlot = (slot: symbol | undefined, tag: string) =>
20 subSlotBase(slot, 'om:' + tag)
21β
22// Signature matches @tanstack/react-query's useMutation.ts.
23export function useMutation<
24 TData = unknown,
25 TError = DefaultError,
26 TVariables = void,
27 TOnMutateResult = unknown,
28>(
29 options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,
30 queryClient?: QueryClient,
31): UseMutationResult<TData, TError, TVariables, TOnMutateResult>
32β
33export function useMutation(options: any, ...rest: Array<any>): any {
34 const [user, slot] = splitSlot(rest)
35 const client = resolveClient(user[0])
36β
37 const [observer] = useState(
38 () => new MutationObserver(client, options),
39 subSlot(slot, 'obs'),
40 )
41β
42 useEffect(
43 () => {
44 observer.setOptions(options)
45 },
46 [observer, options],
47 subSlot(slot, 'eff'),
48 )
49β
50 const result = useSyncExternalStore(
51 useCallback(
52 (onStoreChange: () => void) =>
53 observer.subscribe(notifyManager.batchCalls(onStoreChange)),
54 [observer],
55 subSlot(slot, 'cb'),
56 ),
57 () => observer.getCurrentResult(),
58 () => observer.getCurrentResult(),
59 subSlot(slot, 'uses'),
60 )
61β
62 const mutate = useCallback(
63 (variables: any, mutateOptions: any) => {
64 observer.mutate(variables, mutateOptions).catch(noop)
65 },
66 [observer],
67 subSlot(slot, 'mut'),
68 )
69β
70 if (
71 result.error &&
72 shouldThrowError(observer.options.throwOnError, [result.error])
73 ) {
74 throw result.error
75 }
76β
77 return { ...result, mutate, mutateAsync: result.mutate }
78}