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`,
28 * `useSuspenseQuery`, and `useSuspenseInfiniteQuery`.
29 *
30 * @param options - The options passed to the calling hook.
31 * @param Observer - The observer class from query-core (`QueryObserver` or
32 * `InfiniteQueryObserver`).
33 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the
34 * one from the nearest context will be used.
35 * @returns The query result, tracking which properties are read unless
36 * `notifyOnChangeProps` is set.
37 * @throws {Error} If `options` is not an object (outside production), or the
38 * query error when it should be thrown to the nearest error boundary (see
39 * `throwOnError`). While suspending, it throws a promise instead.
40 */
41export function useBaseQuery<
42 TQueryFnData,
43 TError,
44 TData,
45 TQueryData,
46 TQueryKey extends QueryKey,
47>(
48 options: UseBaseQueryOptions<
49 TQueryFnData,
50 TError,
51 TData,
52 TQueryData,
53 TQueryKey
54 >,
55 Observer: typeof QueryObserver,
56 queryClient?: QueryClient,
57): QueryObserverResult<TData, TError> {
58 if (process.env.NODE_ENV !== 'production') {
59 if (typeof options !== 'object' || Array.isArray(options)) {
60 throw new Error(
61 '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',
62 )
63 }
64 }
65β
66 const isRestoring = useIsRestoring()
67 const errorResetBoundary = useQueryErrorResetBoundary()
68 const client = useQueryClient(queryClient)
69 const defaultedOptions = client.defaultQueryOptions(options)
70β
71 const query = client
72 .getQueryCache()
73 .get<TQueryFnData, TError, TQueryData, TQueryKey>(
74 defaultedOptions.queryHash,
75 )
76β
77 if (process.env.NODE_ENV !== 'production') {
78 if (!defaultedOptions.queryFn) {
79 console.error(
80 `[${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`,
81 )
82 }
83 }
84β
85 const subscribed = options.subscribed !== false
86β
87 // Make sure results are optimistically set in fetching state before subscribing or updating options
88 defaultedOptions._optimisticResults = isRestoring
89 ? 'isRestoring'
90 : subscribed
91 ? 'optimistic'
92 : undefined
93β
94 ensureSuspenseTimers(defaultedOptions)
95 ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query)
96β
97 useClearResetErrorBoundary(errorResetBoundary)
98β
99 const [observer] = useState(
100 () =>
101 new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
102 client,
103 defaultedOptions,
104 ),
105 )
106β
107 // note: this must be called before useSyncExternalStore
108 const result = observer.getOptimisticResult(defaultedOptions)
109β
110 const shouldSubscribe = !isRestoring && subscribed
111 useSyncExternalStore(
112 useCallback(
113 (onStoreChange) => {
114 const unsubscribe = shouldSubscribe
115 ? observer.subscribe(notifyManager.batchCalls(onStoreChange))
116 : noop
117β
118 // Update result to make sure we did not miss any query updates
119 // between creating the observer and subscribing to it.
120 observer.updateResult()
121β
122 return unsubscribe
123 },
124 [observer, shouldSubscribe],
125 ),
126 () => observer.getCurrentResult(),
127 )
128β
129 useEffect(() => {
130 observer.setOptions(defaultedOptions)
131 }, [defaultedOptions, observer])
132β
133 // Handle suspense
134 if (shouldSuspend(defaultedOptions, result)) {
135 throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
136 }
137β
138 // Handle error boundary
139 if (
140 getHasError({
141 result,
142 errorResetBoundary,
143 throwOnError: defaultedOptions.throwOnError,
144 query,
145 suspense: defaultedOptions.suspense,
146 })
147 ) {
148 throw result.error
149 }
150β
151 // Handle result property usage tracking
152 return !defaultedOptions.notifyOnChangeProps
153 ? observer.trackResult(result)
154 : result
155}