Open History to see the last commit
1'use client'
2import * as React from 'react'
3β
4import type { QueryClient, QueryKey, QueryObserver } from '@tanstack/query-core'
5import { notifyManager } from '@tanstack/query-core'
6import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'
7import { useQueryClient } from './QueryClientProvider'
8import type { UseBaseQueryOptions } from './types'
9import { useIsRestoring } from './isRestoring'
10import {
11 ensurePreventErrorBoundaryRetry,
12 getHasError,
13 useClearResetErrorBoundary,
14} from './errorBoundaryUtils'
15import { ensureStaleTime, shouldSuspend, fetchOptimistic } from './suspense'
16β
17export function useBaseQuery<
18 TQueryFnData,
19 TError,
20 TData,
21 TQueryData,
22 TQueryKey extends QueryKey,
23>(
24 options: UseBaseQueryOptions<
25 TQueryFnData,
26 TError,
27 TData,
28 TQueryData,
29 TQueryKey
30 >,
31 Observer: typeof QueryObserver,
32 queryClient?: QueryClient,
33) {
34 const client = useQueryClient(queryClient)
35 const isRestoring = useIsRestoring()
36 const errorResetBoundary = useQueryErrorResetBoundary()
37 const defaultedOptions = client.defaultQueryOptions(options)
38β
39 // Make sure results are optimistically set in fetching state before subscribing or updating options
40 defaultedOptions._optimisticResults = isRestoring
41 ? 'isRestoring'
42 : 'optimistic'
43β
44 ensureStaleTime(defaultedOptions)
45 ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary)
46β
47 useClearResetErrorBoundary(errorResetBoundary)
48β
49 const [observer] = React.useState(
50 () =>
51 new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
52 client,
53 defaultedOptions,
54 ),
55 )
56β
57 const result = observer.getOptimisticResult(defaultedOptions)
58β
59 React.useSyncExternalStore(
60 React.useCallback(
61 (onStoreChange) =>
62 isRestoring
63 ? () => undefined
64 : observer.subscribe(notifyManager.batchCalls(onStoreChange)),
65 [observer, isRestoring],
66 ),
67 () => observer.getCurrentResult(),
68 () => observer.getCurrentResult(),
69 )
70β
71 React.useEffect(() => {
72 // Do not notify on updates because of changes in the options because
73 // these changes should already be reflected in the optimistic result.
74 observer.setOptions(defaultedOptions, { listeners: false })
75 }, [defaultedOptions, observer])
76β
77 // Handle suspense
78 if (shouldSuspend(defaultedOptions, result, isRestoring)) {
79 throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
80 }
81β
82 // Handle error boundary
83 if (
84 getHasError({
85 result,
86 errorResetBoundary,
87 throwOnError: defaultedOptions.throwOnError,
88 query: observer.getCurrentQuery(),
89 })
90 ) {
91 throw result.error
92 }
93β
94 // Handle result property usage tracking
95 return !defaultedOptions.notifyOnChangeProps
96 ? observer.trackResult(result)
97 : result
98}