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

useBaseQuery.ts

171 lines5.4 KB

1'use client'
2import * as React from 'react'
3​
4import { noop, 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 './IsRestoringProvider'
13import { useQueryStrictMode } from './QueryStrictModeContext'
14import { checkQueryStrictMode } from './QueryStrictModeDev'
15import {
16 ensureSuspenseTimers,
17 fetchOptimistic,
18 shouldSuspend,
19} from './suspense'
20import type {
21 QueryClient,
22 QueryKey,
23 QueryObserver,
24 QueryObserverResult,
25} from '@tanstack/query-core'
26import type { UseBaseQueryOptions } from './types'
27​
28/**
29 * Base implementation shared by `useQuery`, `useInfiniteQuery`, `useSuspenseQuery`, and
30 * `useSuspenseInfiniteQuery`.
31 * @param options - The options passed to the calling hook.
32 * @param Observer - The observer class from query-core (`QueryObserver` or
33 * `InfiniteQueryObserver`).
34 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest
35 * context will be used.
36 * @returns The query result, tracking which properties are read unless `notifyOnChangeProps` is
37 * set.
38 * @throws {Error} If `options` is not an object (outside production), or the query error when it should be
39 * thrown to the nearest error boundary (see `throwOnError`). While suspending, it throws a promise instead.
40 */
41export function useBaseQuery<
42 TQueryFnData,
43 TError,
44 TData,
45 TQueryData,
46 TQueryKey extends QueryKey,
47>(
48 options: UseBaseQueryOptions<
49 TQueryFnData,
50 TError,
51 TData,
52 TQueryData,
53 TQueryKey
54 >,
55 Observer: typeof QueryObserver,
56 queryClient?: QueryClient,
57): QueryObserverResult<TData, TError> {
58 if (process.env.NODE_ENV !== 'production') {
59 if (typeof options !== 'object' || Array.isArray(options)) {
60 throw new Error(
61 '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',
62 )
63 }
64 }
65​
66 const isRestoring = useIsRestoring()
67 const errorResetBoundary = useQueryErrorResetBoundary()
68 const strictMode =
69 process.env.NODE_ENV !== 'production'
70 ? // The condition is constant for a build, so the hooks are always called in the same order
71 // eslint-disable-next-line react-hooks-js/rules-of-hooks
72 useQueryStrictMode()
73 : null
74 const client = useQueryClient(queryClient)
75 const defaultedOptions = client.defaultQueryOptions(options)
76​
77 const query = client
78 .getQueryCache()
79 .get<TQueryFnData, TError, TQueryData, TQueryKey>(
80 defaultedOptions.queryHash,
81 )
82​
83 if (process.env.NODE_ENV !== 'production') {
84 if (!defaultedOptions.queryFn) {
85 console.error(
86 `[${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`,
87 )
88 }
89 }
90​
91 const subscribed = options.subscribed !== false
92​
93 // Make sure results are optimistically set in fetching state before subscribing or updating options
94 defaultedOptions._optimisticResults = isRestoring
95 ? 'isRestoring'
96 : subscribed
97 ? 'optimistic'
98 : undefined
99​
100 ensureSuspenseTimers(defaultedOptions)
101 ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query)
102 useClearResetErrorBoundary(errorResetBoundary)
103​
104 const [observer] = React.useState(
105 () =>
106 new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
107 client,
108 defaultedOptions,
109 ),
110 )
111​
112 // note: this must be called before useSyncExternalStore
113 const result = observer.getOptimisticResult(defaultedOptions)
114​
115 const shouldSubscribe = !isRestoring && subscribed
116 React.useSyncExternalStore(
117 React.useCallback(
118 (onStoreChange) => {
119 const unsubscribe = shouldSubscribe
120 ? observer.subscribe(notifyManager.batchCalls(onStoreChange))
121 : noop
122​
123 // Update result to make sure we did not miss any query updates
124 // between creating the observer and subscribing to it.
125 observer.updateResult()
126​
127 return unsubscribe
128 },
129 [observer, shouldSubscribe],
130 ),
131 () => observer.getCurrentResult(),
132 () => observer.getCurrentResult(),
133 )
134​
135 React.useEffect(() => {
136 observer.setOptions(defaultedOptions)
137 }, [defaultedOptions, observer])
138​
139 if (process.env.NODE_ENV !== 'production' && !isRestoring) {
140 checkQueryStrictMode(
141 strictMode,
142 client.getQueryCache(),
143 defaultedOptions.queryHash,
144 result,
145 !!defaultedOptions.suspense,
146 )
147 }
148​
149 // Handle suspense
150 if (shouldSuspend(defaultedOptions, result)) {
151 throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
152 }
153​
154 // Handle error boundary
155 if (
156 getHasError({
157 result,
158 errorResetBoundary,
159 throwOnError: defaultedOptions.throwOnError,
160 query,
161 suspense: defaultedOptions.suspense,
162 })
163 ) {
164 throw result.error
165 }
166​
167 // Handle result property usage tracking
168 return !defaultedOptions.notifyOnChangeProps
169 ? observer.trackResult(result)
170 : result