Open History to see the last commit
1'use client'
2import * as React from 'react'
3β
4import { notifyManager } from '@tanstack/query-core'
5import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'
6import { useQueryClient } from './QueryClientProvider'
7import { useIsRestoring } from './isRestoring'
8import {
9 ensurePreventErrorBoundaryRetry,
10 getHasError,
11 useClearResetErrorBoundary,
12} from './errorBoundaryUtils'
13import {
14 ensureSuspenseTimers,
15 fetchOptimistic,
16 shouldSuspend,
17} from './suspense'
18import type { UseBaseQueryOptions } from './types'
19import type {
20 QueryClient,
21 QueryKey,
22 QueryObserver,
23 QueryObserverResult,
24} from '@tanstack/query-core'
25β
26export function useBaseQuery<
27 TQueryFnData,
28 TError,
29 TData,
30 TQueryData,
31 TQueryKey extends QueryKey,
32>(
33 options: UseBaseQueryOptions<
34 TQueryFnData,
35 TError,
36 TData,
37 TQueryData,
38 TQueryKey
39 >,
40 Observer: typeof QueryObserver,
41 queryClient?: QueryClient,
42): QueryObserverResult<TData, TError> {
43 if (process.env.NODE_ENV !== 'production') {
44 if (typeof options !== 'object' || Array.isArray(options)) {
45 throw new Error(
46 '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',
47 )
48 }
49 }
50β
51 const client = useQueryClient(queryClient)
52 const isRestoring = useIsRestoring()
53 const errorResetBoundary = useQueryErrorResetBoundary()
54 const defaultedOptions = client.defaultQueryOptions(options)
55β
56 ;(client.getDefaultOptions().queries as any)?._experimental_beforeQuery?.(
57 defaultedOptions,
58 )
59β
60 // Make sure results are optimistically set in fetching state before subscribing or updating options
61 defaultedOptions._optimisticResults = isRestoring
62 ? 'isRestoring'
63 : 'optimistic'
64β
65 ensureSuspenseTimers(defaultedOptions)
66 ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary)
67β
68 useClearResetErrorBoundary(errorResetBoundary)
69β
70 const [observer] = React.useState(
71 () =>
72 new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
73 client,
74 defaultedOptions,
75 ),
76 )
77β
78 const result = observer.getOptimisticResult(defaultedOptions)
79β
80 React.useSyncExternalStore(
81 React.useCallback(
82 (onStoreChange) => {
83 const unsubscribe = isRestoring
84 ? () => undefined
85 : observer.subscribe(notifyManager.batchCalls(onStoreChange))
86β
87 // Update result to make sure we did not miss any query updates
88 // between creating the observer and subscribing to it.
89 observer.updateResult()
90β
91 return unsubscribe
92 },
93 [observer, isRestoring],
94 ),
95 () => observer.getCurrentResult(),
96 () => observer.getCurrentResult(),
97 )
98β
99 React.useEffect(() => {
100 // Do not notify on updates because of changes in the options because
101 // these changes should already be reflected in the optimistic result.
102 observer.setOptions(defaultedOptions, { listeners: false })
103 }, [defaultedOptions, observer])
104β
105 // Handle suspense
106 if (shouldSuspend(defaultedOptions, result)) {
107 // Do the same thing as the effect right above because the effect won't run
108 // when we suspend but also, the component won't re-mount so our observer would
109 // be out of date.
110 observer.setOptions(defaultedOptions, { listeners: false })
111 throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
112 }
113β
114 // Handle error boundary
115 if (
116 getHasError({
117 result,
118 errorResetBoundary,
119 throwOnError: defaultedOptions.throwOnError,
120 query: client
121 .getQueryCache()
122 .get<
123 TQueryFnData,
124 TError,
125 TQueryData,
126 TQueryKey
127 >(defaultedOptions.queryHash),
128 })
129 ) {
130 throw result.error
131 }
132β
133 ;(client.getDefaultOptions().queries as any)?._experimental_afterQuery?.(
134 defaultedOptions,
135 result,
136 )
137β
138 // Handle result property usage tracking
139 return !defaultedOptions.notifyOnChangeProps
140 ? observer.trackResult(result)
141 : result
142}