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

useBaseQuery.ts

169 lines5.1 KB

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