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

useBaseQuery.ts

152 lines4.8 KB

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