Open History to see the last commit
1'use client'
2import * as React from 'react'
3β
4import { noop, notifyManager } from '@tanstack/query-core'
5import { useQueryClient } from './QueryClientProvider'
6import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'
7import {
8 ensurePreventErrorBoundaryRetry,
9 getHasError,
10 useClearResetErrorBoundary,
11} from './errorBoundaryUtils'
12import { useIsRestoring } from './IsRestoringProvider'
13import {
14 ensureSuspenseTimers,
15 fetchOptimistic,
16 shouldSuspend,
17 willFetch,
18} from './suspense'
19import type {
20 QueryClient,
21 QueryKey,
22 QueryObserver,
23 QueryObserverResult,
24} from '@tanstack/query-core'
25import type { UseBaseQueryOptions } from './types'
26β
27export function useBaseQuery<
28 TQueryFnData,
29 TError,
30 TData,
31 TQueryData,
32 TQueryKey extends QueryKey,
33>(
34 options: UseBaseQueryOptions<
35 TQueryFnData,
36 TError,
37 TData,
38 TQueryData,
39 TQueryKey
40 >,
41 Observer: typeof QueryObserver,
42 queryClient?: QueryClient,
43): QueryObserverResult<TData, TError> {
44 if (process.env.NODE_ENV !== 'production') {
45 if (typeof options !== 'object' || Array.isArray(options)) {
46 throw new Error(
47 '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',
48 )
49 }
50 }
51β
52 const isRestoring = useIsRestoring()
53 const errorResetBoundary = useQueryErrorResetBoundary()
54 const client = useQueryClient(queryClient)
55 const defaultedOptions = client.defaultQueryOptions(options)
56 ;(client.getDefaultOptions().queries as any)?._experimental_beforeQuery?.(
57 defaultedOptions,
58 )
59β
60 const query = client
61 .getQueryCache()
62 .get<
63 TQueryFnData,
64 TError,
65 TQueryData,
66 TQueryKey
67 >(defaultedOptions.queryHash)
68β
69 if (process.env.NODE_ENV !== 'production') {
70 if (!defaultedOptions.queryFn) {
71 console.error(
72 `[${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`,
73 )
74 }
75 }
76β
77 // Make sure results are optimistically set in fetching state before subscribing or updating options
78 defaultedOptions._optimisticResults = isRestoring
79 ? 'isRestoring'
80 : 'optimistic'
81β
82 ensureSuspenseTimers(defaultedOptions)
83 ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query)
84 useClearResetErrorBoundary(errorResetBoundary)
85β
86 // this needs to be invoked before creating the Observer because that can create a cache entry
87 const isNewCacheEntry = !client
88 .getQueryCache()
89 .get(defaultedOptions.queryHash)
90β
91 const [observer] = React.useState(
92 () =>
93 new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
94 client,
95 defaultedOptions,
96 ),
97 )
98β
99 // note: this must be called before useSyncExternalStore
100 const result = observer.getOptimisticResult(defaultedOptions)
101β
102 const shouldSubscribe = !isRestoring && options.subscribed !== false
103 React.useSyncExternalStore(
104 React.useCallback(
105 (onStoreChange) => {
106 const unsubscribe = shouldSubscribe
107 ? observer.subscribe(notifyManager.batchCalls(onStoreChange))
108 : noop
109β
110 // Update result to make sure we did not miss any query updates
111 // between creating the observer and subscribing to it.
112 observer.updateResult()
113β
114 return unsubscribe
115 },
116 [observer, shouldSubscribe],
117 ),
118 () => observer.getCurrentResult(),
119 () => observer.getCurrentResult(),
120 )
121β
122 React.useEffect(() => {
123 observer.setOptions(defaultedOptions)
124 }, [defaultedOptions, observer])
125β
126 // Handle suspense
127 if (shouldSuspend(defaultedOptions, result)) {
128 throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
129 }
130β
131 // Handle error boundary
132 if (
133 getHasError({
134 result,
135 errorResetBoundary,
136 throwOnError: defaultedOptions.throwOnError,
137 query,
138 suspense: defaultedOptions.suspense,
139 })
140 ) {
141 throw result.error
142 }
143β
144 ;(client.getDefaultOptions().queries as any)?._experimental_afterQuery?.(
145 defaultedOptions,
146 result,
147 )
148β
149 if (
150 defaultedOptions.experimental_prefetchInRender &&
151 !client.isServer &&
152 willFetch(result, isRestoring)
153 ) {
154 const promise = isNewCacheEntry
155 ? // Fetch immediately on render in order to ensure `.promise` is resolved even if the component is unmounted
156 fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
157 : // subscribe to the "cache promise" so that we can finalize the currentThenable once data comes in
158 query?.promise
159β
160 promise?.catch(noop).finally(() => {
161 // `.updateResult()` will trigger `.#currentThenable` to finalize
162 observer.updateResult()
163 })
164 }
165β
166 // Handle result property usage tracking
167 return !defaultedOptions.notifyOnChangeProps
168 ? observer.trackResult(result)
169 : result
170}