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

useBaseQuery.ts

169 lines5.0 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 // 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 cacheEntry = client.getQueryCache().get(defaultedOptions.queryHash)
74​
75 const [observer] = React.useState(
76 () =>
77 new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
78 client,
79 defaultedOptions,
80 ),
81 )
82​
83 const result = observer.getOptimisticResult(defaultedOptions)
84​
85 React.useSyncExternalStore(
86 React.useCallback(
87 (onStoreChange) => {
88 const unsubscribe = isRestoring
89 ? noop
90 : observer.subscribe(notifyManager.batchCalls(onStoreChange))
91​
92 // Update result to make sure we did not miss any query updates
93 // between creating the observer and subscribing to it.
94 observer.updateResult()
95​
96 return unsubscribe
97 },
98 [observer, isRestoring],
99 ),
100 () => observer.getCurrentResult(),
101 () => observer.getCurrentResult(),
102 )
103​
104 React.useEffect(() => {
105 // Do not notify on updates because of changes in the options because
106 // these changes should already be reflected in the optimistic result.
107 observer.setOptions(defaultedOptions, { listeners: false })
108 }, [defaultedOptions, observer])
109​
110 // Handle suspense
111 if (shouldSuspend(defaultedOptions, result)) {
112 throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
113 }
114​
115 // Handle error boundary
116 if (
117 getHasError({
118 result,
119 errorResetBoundary,
120 throwOnError: defaultedOptions.throwOnError,
121 query: client
122 .getQueryCache()
123 .get<
124 TQueryFnData,
125 TError,
126 TQueryData,
127 TQueryKey
128 >(defaultedOptions.queryHash),
129 })
130 ) {
131 throw result.error
132 }
133​
134 ;(client.getDefaultOptions().queries as any)?._experimental_afterQuery?.(
135 defaultedOptions,
136 result,
137 )
138​
139 if (
140 defaultedOptions.experimental_prefetchInRender &&
141 !isServer &&
142 willFetch(result, isRestoring)
143 ) {
144 // This fetching in the render should likely be done as part of the getOptimisticResult() considering https://github.com/TanStack/query/issues/8507
145 const state = cacheEntry?.state
146​
147 const shouldFetch =
148 !state ||
149 (state.data === undefined &&
150 state.status === 'pending' &&
151 state.fetchStatus === 'idle')
152​
153 const promise = shouldFetch
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