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'
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 const subscribed = options.subscribed !== false
84​
85 // Make sure results are optimistically set in fetching state before subscribing or updating options
86 defaultedOptions._optimisticResults = isRestoring
87 ? 'isRestoring'
88 : subscribed
89 ? 'optimistic'
90 : undefined
91​
92 ensureSuspenseTimers(defaultedOptions)
93 ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query)
94​
95 useClearResetErrorBoundary(errorResetBoundary)
96​
97 const [observer] = useState(
98 () =>
99 new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
100 client,
101 defaultedOptions,
102 ),
103 )
104​
105 const reader = observer.createResultReader(defaultedOptions)
106​
107 // Suspend before registering external-store effects for this render.
108 if (shouldSuspend(defaultedOptions, reader.getSnapshot())) {
109 throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
110 }
111​
112 const shouldSubscribe = !isRestoring && subscribed
113 const result = useSyncExternalStore(
114 useCallback(
115 (onStoreChange) => {
116 const unsubscribe = shouldSubscribe
117 ? observer.subscribe(notifyManager.batchCalls(onStoreChange))
118 : noop
119​
120 // Update result to make sure we did not miss any query updates
121 // between creating the observer and subscribing to it.
122 observer.updateResult()
123​
124 return unsubscribe
125 },
126 [observer, shouldSubscribe],
127 ),
128 reader.getSnapshot,
129 )
130​
131 useEffect(() => {
132 reader.commit()
133 }, [reader])
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