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

useBaseQuery.ts

155 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`,
28 * `useSuspenseQuery`, and `useSuspenseInfiniteQuery`.
29 *
30 * @param options - The options passed to the calling hook.
31 * @param Observer - The observer class from query-core (`QueryObserver` or
32 * `InfiniteQueryObserver`).
33 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the
34 * one from the nearest context will be used.
35 * @returns The query result, tracking which properties are read unless
36 * `notifyOnChangeProps` is set.
37 * @throws {Error} If `options` is not an object (outside production), or the
38 * query error when it should be thrown to the nearest error boundary (see
39 * `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 client = useQueryClient(queryClient)
69 const defaultedOptions = client.defaultQueryOptions(options)
70​
71 const query = client
72 .getQueryCache()
73 .get<TQueryFnData, TError, TQueryData, TQueryKey>(
74 defaultedOptions.queryHash,
75 )
76​
77 if (process.env.NODE_ENV !== 'production') {
78 if (!defaultedOptions.queryFn) {
79 console.error(
80 `[${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`,
81 )
82 }
83 }
84​
85 const subscribed = options.subscribed !== false
86​
87 // Make sure results are optimistically set in fetching state before subscribing or updating options
88 defaultedOptions._optimisticResults = isRestoring
89 ? 'isRestoring'
90 : subscribed
91 ? 'optimistic'
92 : undefined
93​
94 ensureSuspenseTimers(defaultedOptions)
95 ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query)
96 useClearResetErrorBoundary(errorResetBoundary)
97​
98 const [observer] = React.useState(
99 () =>
100 new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
101 client,
102 defaultedOptions,
103 ),
104 )
105​
106 // note: this must be called before useSyncExternalStore
107 const result = observer.getOptimisticResult(defaultedOptions)
108​
109 const shouldSubscribe = !isRestoring && subscribed
110 React.useSyncExternalStore(
111 React.useCallback(
112 (onStoreChange) => {
113 const unsubscribe = shouldSubscribe
114 ? observer.subscribe(notifyManager.batchCalls(onStoreChange))
115 : noop
116​
117 // Update result to make sure we did not miss any query updates
118 // between creating the observer and subscribing to it.
119 observer.updateResult()
120​
121 return unsubscribe
122 },
123 [observer, shouldSubscribe],
124 ),
125 () => observer.getCurrentResult(),
126 () => observer.getCurrentResult(),
127 )
128​
129 React.useEffect(() => {
130 observer.setOptions(defaultedOptions)
131 }, [defaultedOptions, observer])
132​
133 // Handle suspense
134 if (shouldSuspend(defaultedOptions, result)) {
135 throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
136 }
137​
138 // Handle error boundary
139 if (
140 getHasError({
141 result,
142 errorResetBoundary,
143 throwOnError: defaultedOptions.throwOnError,
144 query,
145 suspense: defaultedOptions.suspense,
146 })
147 ) {
148 throw result.error
149 }
150​
151 // Handle result property usage tracking
152 return !defaultedOptions.notifyOnChangeProps
153 ? observer.trackResult(result)
154 : result