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

useBaseQuery.ts

152 lines4.8 KB

1'use client'
2import { noop, notifyManager } from '@tanstack/query-core'
3import * as React from 'react'
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 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 useClearResetErrorBoundary(errorResetBoundary)
94​
95 const [observer] = React.useState(
96 () =>
97 new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
98 client,
99 defaultedOptions,
100 ),
101 )
102​
103 // note: this must be called before useSyncExternalStore
104 const result = observer.getOptimisticResult(defaultedOptions)
105​
106 React.useEffect(() => {
107 observer.setOptions(defaultedOptions)
108 }, [defaultedOptions, observer])
109​
110 const shouldSubscribe = !isRestoring && subscribed
111 React.useSyncExternalStore(
112 React.useCallback(
113 (onStoreChange) => {
114 const unsubscribe = shouldSubscribe
115 ? observer.subscribe(notifyManager.batchCalls(onStoreChange))
116 : noop
117​
118 // Update result to make sure we did not miss any query updates
119 // between creating the observer and subscribing to it.
120 observer.updateResult()
121​
122 return unsubscribe
123 },
124 [observer, shouldSubscribe],
125 ),
126 () => observer.getCurrentResult(),
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