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

useBaseQuery.ts

173 lines5.3 KB

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 if (process.env.NODE_ENV !== 'production') {
63 if (!defaultedOptions.queryFn) {
64 console.error(
65 `[${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`,
66 )
67 }
68 }
69​
70 // Make sure results are optimistically set in fetching state before subscribing or updating options
71 defaultedOptions._optimisticResults = isRestoring
72 ? 'isRestoring'
73 : 'optimistic'
74​
75 ensureSuspenseTimers(defaultedOptions)
76 ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary)
77​
78 useClearResetErrorBoundary(errorResetBoundary)
79​
80 // this needs to be invoked before creating the Observer because that can create a cache entry
81 const isNewCacheEntry = !client
82 .getQueryCache()
83 .get(defaultedOptions.queryHash)
84​
85 const [observer] = React.useState(
86 () =>
87 new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
88 client,
89 defaultedOptions,
90 ),
91 )
92​
93 // note: this must be called before useSyncExternalStore
94 const result = observer.getOptimisticResult(defaultedOptions)
95​
96 const shouldSubscribe = !isRestoring && options.subscribed !== false
97 React.useSyncExternalStore(
98 React.useCallback(
99 (onStoreChange) => {
100 const unsubscribe = shouldSubscribe
101 ? observer.subscribe(notifyManager.batchCalls(onStoreChange))
102 : noop
103​
104 // Update result to make sure we did not miss any query updates
105 // between creating the observer and subscribing to it.
106 observer.updateResult()
107​
108 return unsubscribe
109 },
110 [observer, shouldSubscribe],
111 ),
112 () => observer.getCurrentResult(),
113 () => observer.getCurrentResult(),
114 )
115​
116 React.useEffect(() => {
117 // Do not notify on updates because of changes in the options because
118 // these changes should already be reflected in the optimistic result.
119 observer.setOptions(defaultedOptions, { listeners: false })
120 }, [defaultedOptions, observer])
121​
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 suspense: defaultedOptions.suspense,
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