Open History to see the last commit
1'use client'
2import * as React from 'react'
3import {
4 MutationObserver,
5 noop,
6 notifyManager,
7 shouldThrowError,
8} from '@tanstack/query-core'
9import { useQueryClient } from './QueryClientProvider'
10import type {
11 UseMutateFunction,
12 UseMutationOptions,
13 UseMutationResult,
14} from './types'
15import type { DefaultError, QueryClient } from '@tanstack/query-core'
16β
17// HOOK
18β
19export function useMutation<
20 TData = unknown,
21 TError = DefaultError,
22 TVariables = void,
23 TScope = unknown,
24>(
25 options: UseMutationOptions<TData, TError, TVariables, TScope>,
26 queryClient?: QueryClient,
27): UseMutationResult<TData, TError, TVariables, TScope> {
28 const client = useQueryClient(queryClient)
29β
30 const [observer] = React.useState(
31 () =>
32 new MutationObserver<TData, TError, TVariables, TScope>(client, options),
33 )
34β
35 React.useEffect(() => {
36 observer.setOptions(options)
37 }, [observer, options])
38β
39 const result = React.useSyncExternalStore(
40 React.useCallback(
41 (onStoreChange) =>
42 observer.subscribe(notifyManager.batchCalls(onStoreChange)),
43 [observer],
44 ),
45 () => observer.getCurrentResult(),
46 () => observer.getCurrentResult(),
47 )
48β
49 const mutate = React.useCallback<
50 UseMutateFunction<TData, TError, TVariables, TScope>
51 >(
52 (variables, mutateOptions) => {
53 observer.mutate(variables, mutateOptions).catch(noop)
54 },
55 [observer],
56 )
57β
58 if (
59 result.error &&
60 shouldThrowError(observer.options.throwOnError, [result.error])
61 ) {
62 throw result.error
63 }
64β
65 return { ...result, mutate, mutateAsync: result.mutate }
66}