Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useBaseQuery.ts

174 lines5.1 KB

1'use client'
2import * as React from 'react'
3​
4import { environmentManager, 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 const subscribed = options.subscribed !== false
78​
79 // Make sure results are optimistically set in fetching state before subscribing or updating options
80 defaultedOptions._optimisticResults = isRestoring
81 ? 'isRestoring'
82 : subscribed
83 ? 'optimistic'
84 : undefined
85​
86 ensureSuspenseTimers(defaultedOptions)
87 ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query)
88 useClearResetErrorBoundary(errorResetBoundary)
89​
90 // this needs to be invoked before creating the Observer because that can create a cache entry
91 const isNewCacheEntry = !client
92 .getQueryCache()
93 .get(defaultedOptions.queryHash)
94​
95 const [observer] = React.useState(
96 () =>
97 new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
98 client,
99 defaultedOptions,
100 ),
101 )
102​
103 // note: this must be called before useSyncExternalStore
104 const result = observer.getOptimisticResult(defaultedOptions)
105​
106 const shouldSubscribe = !isRestoring && subscribed
107 React.useSyncExternalStore(
108 React.useCallback(
109 (onStoreChange) => {
110 const unsubscribe = shouldSubscribe
111 ? observer.subscribe(notifyManager.batchCalls(onStoreChange))
112 : noop
113​
114 // Update result to make sure we did not miss any query updates
115 // between creating the observer and subscribing to it.
116 observer.updateResult()
117​
118 return unsubscribe
119 },
120 [observer, shouldSubscribe],
121 ),
122 () => observer.getCurrentResult(),
123 () => observer.getCurrentResult(),
124 )
125​
126 React.useEffect(() => {
127 observer.setOptions(defaultedOptions)
128 }, [defaultedOptions, observer])
129​
130 // Handle suspense
131 if (shouldSuspend(defaultedOptions, result)) {
132 throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
133 }
134​
135 // Handle error boundary
136 if (
137 getHasError({
138 result,
139 errorResetBoundary,
140 throwOnError: defaultedOptions.throwOnError,
141 query,
142 suspense: defaultedOptions.suspense,
143 })
144 ) {
145 throw result.error
146 }
147​
148 ;(client.getDefaultOptions().queries as any)?._experimental_afterQuery?.(
149 defaultedOptions,
150 result,
151 )
152​
153 if (
154 defaultedOptions.experimental_prefetchInRender &&
155 !environmentManager.isServer() &&
156 willFetch(result, isRestoring)
157 ) {
158 const promise = isNewCacheEntry
159 ? // Fetch immediately on render in order to ensure `.promise` is resolved even if the component is unmounted
160 fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
161 : // subscribe to the "cache promise" so that we can finalize the currentThenable once data comes in
162 query?.promise
163​
164 promise?.catch(noop).finally(() => {
165 // `.updateResult()` will trigger `.#currentThenable` to finalize
166 observer.updateResult()
167 })
168 }
169​
170 // Handle result property usage tracking
171 return !defaultedOptions.notifyOnChangeProps
172 ? observer.trackResult(result)
173 : result