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

useBaseQuery.ts

153 lines4.8 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 {
14 ensureSuspenseTimers,
15 fetchOptimistic,
16 shouldSuspend,
17} from './suspense'
18import type {
19 QueryClient,
20 QueryKey,
21 QueryObserver,
22 QueryObserverResult,
23} from '@tanstack/query-core'
24import type { UseBaseQueryOptions } from './types'
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 useClearResetErrorBoundary(errorResetBoundary)
95​
96 const [observer] = React.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 const shouldSubscribe = !isRestoring && subscribed
108 React.useSyncExternalStore(
109 React.useCallback(
110 (onStoreChange) => {
111 const unsubscribe = shouldSubscribe
112 ? observer.subscribe(notifyManager.batchCalls(onStoreChange))
113 : noop
114​
115 // Update result to make sure we did not miss any query updates
116 // between creating the observer and subscribing to it.
117 observer.updateResult()
118​
119 return unsubscribe
120 },
121 [observer, shouldSubscribe],
122 ),
123 () => observer.getCurrentResult(),
124 () => observer.getCurrentResult(),
125 )
126​
127 React.useEffect(() => {
128 observer.setOptions(defaultedOptions)
129 }, [defaultedOptions, observer])
130​
131 // Handle suspense
132 if (shouldSuspend(defaultedOptions, result)) {
133 throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
134 }
135​
136 // Handle error boundary
137 if (
138 getHasError({
139 result,
140 errorResetBoundary,
141 throwOnError: defaultedOptions.throwOnError,
142 query,
143 suspense: defaultedOptions.suspense,
144 })
145 ) {
146 throw result.error
147 }
148​
149 // Handle result property usage tracking
150 return !defaultedOptions.notifyOnChangeProps
151 ? observer.trackResult(result)
152 : result