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

useBaseQuery.ts

170 lines5.1 KB

1'use client'
2import * as React from 'react'
3​
4import { isServer, 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​
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] = React.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 React.useSyncExternalStore(
97 React.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 () => observer.getCurrentResult(),
113 )
114​
115 React.useEffect(() => {
116 observer.setOptions(defaultedOptions)
117 }, [defaultedOptions, observer])
118​
119 // Handle suspense
120 if (shouldSuspend(defaultedOptions, result)) {
121 throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
122 }
123​
124 // Handle error boundary
125 if (
126 getHasError({
127 result,
128 errorResetBoundary,
129 throwOnError: defaultedOptions.throwOnError,
130 query: client
131 .getQueryCache()
132 .get<
133 TQueryFnData,
134 TError,
135 TQueryData,
136 TQueryKey
137 >(defaultedOptions.queryHash),
138 suspense: defaultedOptions.suspense,
139 })
140 ) {
141 throw result.error
142 }
143​
144 ;(client.getDefaultOptions().queries as any)?._experimental_afterQuery?.(
145 defaultedOptions,
146 result,
147 )
148​
149 if (
150 defaultedOptions.experimental_prefetchInRender &&
151 !isServer &&
152 willFetch(result, isRestoring)
153 ) {
154 const promise = isNewCacheEntry
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