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

useBaseQuery.ts

149 lines4.7 KB

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