Open History to see the last commit
1'use client'
2import * as React from 'react'
3β
4import { isServer, 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 './isRestoring'
13import {
14 ensureSuspenseTimers,
15 fetchOptimistic,
16 shouldSuspend,
17 willFetch,
18} from './suspense'
19import { noop } from './utils'
20import type {
21 QueryClient,
22 QueryKey,
23 QueryObserver,
24 QueryObserverResult,
25} from '@tanstack/query-core'
26import type { UseBaseQueryOptions } from './types'
27β
28export function useBaseQuery<
29 TQueryFnData,
30 TError,
31 TData,
32 TQueryData,
33 TQueryKey extends QueryKey,
34>(
35 options: UseBaseQueryOptions<
36 TQueryFnData,
37 TError,
38 TData,
39 TQueryData,
40 TQueryKey
41 >,
42 Observer: typeof QueryObserver,
43 queryClient?: QueryClient,
44): QueryObserverResult<TData, TError> {
45 if (process.env.NODE_ENV !== 'production') {
46 if (typeof options !== 'object' || Array.isArray(options)) {
47 throw new Error(
48 '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',
49 )
50 }
51 }
52β
53 const client = useQueryClient(queryClient)
54 const isRestoring = useIsRestoring()
55 const errorResetBoundary = useQueryErrorResetBoundary()
56 const defaultedOptions = client.defaultQueryOptions(options)
57β
58 ;(client.getDefaultOptions().queries as any)?._experimental_beforeQuery?.(
59 defaultedOptions,
60 )
61β
62 // Make sure results are optimistically set in fetching state before subscribing or updating options
63 defaultedOptions._optimisticResults = isRestoring
64 ? 'isRestoring'
65 : 'optimistic'
66β
67 ensureSuspenseTimers(defaultedOptions)
68 ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary)
69β
70 useClearResetErrorBoundary(errorResetBoundary)
71β
72 // this needs to be invoked before creating the Observer because that can create a cache entry
73 const cacheEntry = client.getQueryCache().get(defaultedOptions.queryHash)
74β
75 const [observer] = React.useState(
76 () =>
77 new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
78 client,
79 defaultedOptions,
80 ),
81 )
82β
84 const result = observer.getOptimisticResult(defaultedOptions)
85β
86 React.useSyncExternalStore(
87 React.useCallback(
88 (onStoreChange) => {
89 const unsubscribe = isRestoring
90 ? noop
91 : observer.subscribe(notifyManager.batchCalls(onStoreChange))
92β
93 // Update result to make sure we did not miss any query updates
94 // between creating the observer and subscribing to it.
95 observer.updateResult()
96β
97 return unsubscribe
98 },
99 [observer, isRestoring],
100 ),
101 () => observer.getCurrentResult(),
102 () => observer.getCurrentResult(),
103 )
104β
105 React.useEffect(() => {
106 // Do not notify on updates because of changes in the options because
107 // these changes should already be reflected in the optimistic result.
108 observer.setOptions(defaultedOptions, { listeners: false })
109 }, [defaultedOptions, observer])
110β
111 // Handle suspense
112 if (shouldSuspend(defaultedOptions, result)) {
113 throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
114 }
115β
116 // Handle error boundary
117 if (
118 getHasError({
119 result,
120 errorResetBoundary,
121 throwOnError: defaultedOptions.throwOnError,
122 query: client
123 .getQueryCache()
124 .get<
125 TQueryFnData,
126 TError,
127 TQueryData,
128 TQueryKey
129 >(defaultedOptions.queryHash),
130 })
131 ) {
132 throw result.error
133 }
134β
135 ;(client.getDefaultOptions().queries as any)?._experimental_afterQuery?.(
136 defaultedOptions,
137 result,
138 )
139β
140 if (
141 defaultedOptions.experimental_prefetchInRender &&
142 !isServer &&
143 willFetch(result, isRestoring)
144 ) {
145 // This fetching in the render should likely be done as part of the getOptimisticResult() considering https://github.com/TanStack/query/issues/8507
146 const state = cacheEntry?.state
147β
148 const shouldFetch =
149 !state ||
150 (state.data === undefined &&
151 state.status === 'pending' &&
152 state.fetchStatus === 'idle')
153β
154 const promise = shouldFetch
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 client.getQueryCache().get(defaultedOptions.queryHash)?.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}