Open History to see the last commit
1import { noop, notifyManager } from '@tanstack/query-core'
2import { useCallback, useEffect, useState } from 'preact/hooks'
3β
4import { useIsRestoring } from './IsRestoringProvider'
5import { useQueryClient } from './QueryClientProvider'
6import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'
7import {
8 ensurePreventErrorBoundaryRetry,
9 getHasError,
10 useClearResetErrorBoundary,
11} from './errorBoundaryUtils'
12import {
13 ensureSuspenseTimers,
14 fetchOptimistic,
15 shouldSuspend,
16} from './suspense'
17import { useSyncExternalStore } from './utils'
18import type { UseBaseQueryOptions } from './types'
19import type {
20 QueryClient,
21 QueryKey,
22 QueryObserver,
23 QueryObserverResult,
24} from '@tanstack/query-core'
25β
26/**
27 * Base implementation shared by `useQuery`, `useInfiniteQuery`, `useSuspenseQuery`, and
28 * `useSuspenseInfiniteQuery`.
29 * @param options - The options passed to the calling hook.
30 * @param Observer - The observer class from query-core (`QueryObserver` or
31 * `InfiniteQueryObserver`).
32 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest
33 * context will be used.
34 * @returns The query result, tracking which properties are read unless `notifyOnChangeProps` is
35 * set.
36 * @throws {Error} If `options` is not an object (outside production), or the query error when it should be
37 * thrown to the nearest error boundary (see `throwOnError`). While suspending, it throws a promise instead.
38 */
39export function useBaseQuery<
40 TQueryFnData,
41 TError,
42 TData,
43 TQueryData,
44 TQueryKey extends QueryKey,
45>(
46 options: UseBaseQueryOptions<
47 TQueryFnData,
48 TError,
49 TData,
50 TQueryData,
51 TQueryKey
52 >,
53 Observer: typeof QueryObserver,
54 queryClient?: QueryClient,
55): QueryObserverResult<TData, TError> {
56 if (process.env.NODE_ENV !== 'production') {
57 if (typeof options !== 'object' || Array.isArray(options)) {
58 throw new Error(
59 'Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object',
60 )
61 }
62 }
63β
64 const isRestoring = useIsRestoring()
65 const errorResetBoundary = useQueryErrorResetBoundary()
66 const client = useQueryClient(queryClient)
67 const defaultedOptions = client.defaultQueryOptions(options)
68β
69 const query = client
70 .getQueryCache()
71 .get<TQueryFnData, TError, TQueryData, TQueryKey>(
72 defaultedOptions.queryHash,
73 )
74β
75 if (process.env.NODE_ENV !== 'production') {
76 if (!defaultedOptions.queryFn) {
77 console.error(
78 `[${defaultedOptions.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`,
79 )
80 }
81 }
82β
83 const subscribed = options.subscribed !== false
84β
85 // Make sure results are optimistically set in fetching state before subscribing or updating options
86 defaultedOptions._optimisticResults = isRestoring
87 ? 'isRestoring'
88 : subscribed
89 ? 'optimistic'
90 : undefined
91β
92 ensureSuspenseTimers(defaultedOptions)
93 ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query)
94β
95 useClearResetErrorBoundary(errorResetBoundary)
96β
97 const [observer] = useState(
98 () =>
99 new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
100 client,
101 defaultedOptions,
102 ),
103 )
104β
105 // note: this must be called before useSyncExternalStore
106 const result = observer.getOptimisticResult(defaultedOptions)
107β
108 useEffect(() => {
109 observer.setOptions(defaultedOptions)
110 }, [defaultedOptions, observer])
111β
112 const shouldSubscribe = !isRestoring && subscribed
113 useSyncExternalStore(
114 useCallback(
115 (onStoreChange) => {
116 const unsubscribe = shouldSubscribe
117 ? observer.subscribe(notifyManager.batchCalls(onStoreChange))
118 : noop
119β
120 // Update result to make sure we did not miss any query updates
121 // between creating the observer and subscribing to it.
122 observer.updateResult()
123β
124 return unsubscribe
125 },
126 [observer, shouldSubscribe],
127 ),
128 () => observer.getCurrentResult(),
129 )
130β
131 // Handle suspense
132 if (shouldSuspend(defaultedOptions, result)) {
133 throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
134 }
135β
136 // Handle error boundary
137 if (
138 getHasError({
139 result,
140 errorResetBoundary,
141 throwOnError: defaultedOptions.throwOnError,
142 query,
143 suspense: defaultedOptions.suspense,
144 })
145 ) {
146 throw result.error
147 }
148β
149 // Handle result property usage tracking
150 return !defaultedOptions.notifyOnChangeProps
151 ? observer.trackResult(result)
152 : result
153}