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