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 isNewCacheEntry = !client
74 .getQueryCache()
75 .get(defaultedOptions.queryHash)
76β
77 const [observer] = React.useState(
78 () =>
79 new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
80 client,
81 defaultedOptions,
82 ),
83 )
84β
85 const [_, setForceUpdate] = React.useState({})
86β
87 const result = observer.getOptimisticResult(defaultedOptions)
88β
89 React.useEffect(() => {
90 if (isRestoring) {
91 return
92 }
93β
94 const unsubscribe = observer.subscribe(
95 notifyManager.batchCalls(() => {
96 setForceUpdate({})
97 }),
98 )
99β
100 // Update result to make sure we did not miss any query updates
101 // between creating the observer and subscribing to it.
102 observer.updateResult()
103β
104 return unsubscribe
105 }, [observer, isRestoring])
106β
107 React.useEffect(() => {
108 if (defaultedOptions.experimental_prefetchInRender) {
109 return
110 }
111 // Do not notify on updates because of changes in the options because
112 // these changes should already be reflected in the optimistic result.
113 observer.setOptions(defaultedOptions, { listeners: false })
114 }, [defaultedOptions, observer])
115β
116 // For prefetchInRender, we need to set the options within the render
117 if (defaultedOptions.experimental_prefetchInRender) {
118 // Do not notify on updates because of changes in the options because
119 // these changes should already be reflected in the optimistic result.
120 observer.setOptions(defaultedOptions, { listeners: false })
121 }
122β
123 // Handle suspense
124 if (shouldSuspend(defaultedOptions, result)) {
125 throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
126 }
127β
128 // Handle error boundary
129 if (
130 getHasError({
131 result,
132 errorResetBoundary,
133 throwOnError: defaultedOptions.throwOnError,
134 query: client
135 .getQueryCache()
136 .get<
137 TQueryFnData,
138 TError,
139 TQueryData,
140 TQueryKey
141 >(defaultedOptions.queryHash),
142 })
143 ) {
144 throw result.error
145 }
146β
147 ;(client.getDefaultOptions().queries as any)?._experimental_afterQuery?.(
148 defaultedOptions,
149 result,
150 )
151β
152 if (
153 defaultedOptions.experimental_prefetchInRender &&
154 !isServer &&
155 willFetch(result, isRestoring)
156 ) {
157 const promise = isNewCacheEntry
158 ? // Fetch immediately on render in order to ensure `.promise` is resolved even if the component is unmounted
159 fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
160 : // subscribe to the "cache promise" so that we can finalize the currentThenable once data comes in
161 client.getQueryCache().get(defaultedOptions.queryHash)?.promise
162β
163 promise?.catch(noop).finally(() => {
164 // `.updateResult()` will trigger `.#currentThenable` to finalize
165 observer.updateResult()
166 })
167 }
168β
169 // Handle result property usage tracking
170 return !defaultedOptions.notifyOnChangeProps
171 ? observer.trackResult(result)
172 : result
173}