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

useBaseQuery.ts

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