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