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

useBaseQuery.ts

163 lines4.4 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 getSuspensePromise,
16 shouldSuspend,
17 use,
18} from './suspense'
19import type {
20 QueryClient,
21 QueryKey,
22 QueryObserver,
23 QueryObserverResult,
24} from '@tanstack/query-core'
25import type { UseBaseQueryOptions } from './types'
26​
27export function useBaseQuery<
28 TQueryFnData,
29 TError,
30 TData,
31 TQueryData,
32 TQueryKey extends QueryKey,
33>(
34 options: UseBaseQueryOptions<
35 TQueryFnData,
36 TError,
37 TData,
38 TQueryData,
39 TQueryKey
40 >,
41 Observer: typeof QueryObserver,
42 queryClient?: QueryClient,
43): QueryObserverResult<TData, TError> {
44 if (process.env.NODE_ENV !== 'production') {
45 if (typeof options !== 'object' || Array.isArray(options)) {
46 throw new Error(
47 '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',
48 )
49 }
50 }
51​
52 const isRestoring = useIsRestoring()
53 const errorResetBoundary = useQueryErrorResetBoundary()
54 const client = useQueryClient(queryClient)
55 const defaultedOptions = client.defaultQueryOptions(options)
56​
57 const query = client
58 .getQueryCache()
59 .get<
60 TQueryFnData,
61 TError,
62 TQueryData,
63 TQueryKey
64 >(defaultedOptions.queryHash)
65​
66 if (process.env.NODE_ENV !== 'production') {
67 if (!defaultedOptions.queryFn) {
68 console.error(
69 `[${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`,
70 )
71 }
72 }
73​
74 const subscribed = options.subscribed !== false
75​
76 // Make sure results are optimistically set in fetching state before subscribing or updating options
77 defaultedOptions._optimisticResults = isRestoring
78 ? 'isRestoring'
79 : subscribed
80 ? 'optimistic'
81 : undefined
82​
83 ensureSuspenseTimers(defaultedOptions)
84 ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query)
85 useClearResetErrorBoundary(errorResetBoundary)
86​
87 const [observer] = React.useState(
88 () =>
89 new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
90 client,
91 defaultedOptions,
92 ),
93 )
94​
95 // note: this must be called before useSyncExternalStore
96 const result = observer.getOptimisticResult(defaultedOptions)
97​
98 const shouldSubscribe = !isRestoring && subscribed
99 React.useSyncExternalStore(
100 React.useCallback(
101 (onStoreChange) => {
102 const unsubscribe = shouldSubscribe
103 ? observer.subscribe(notifyManager.batchCalls(onStoreChange))
104 : noop
105​
106 // Update result to make sure we did not miss any query updates
107 // between creating the observer and subscribing to it.
108 observer.updateResult()
109​
110 return unsubscribe
111 },
112 [observer, shouldSubscribe],
113 ),
114 () => observer.getCurrentResult(),
115 () => observer.getCurrentResult(),
116 )
117​
118 React.useEffect(() => {
119 observer.setOptions(defaultedOptions)
120 }, [defaultedOptions, observer])
121​
122 // Handle suspense
123 if (defaultedOptions.suspense) {
124 const suspenseQuery = client.getQueryCache().build(client, defaultedOptions)
125 const suspend = shouldSuspend(
126 defaultedOptions,
127 result,
128 errorResetBoundary,
129 suspenseQuery,
130 )
131​
132 if (suspend !== undefined) {
133 const promise = getSuspensePromise(
134 defaultedOptions,
135 observer,
136 errorResetBoundary,
137 suspenseQuery,
138 )
139​
140 if (suspend) {
141 use(promise)
142 }
143 }
144 }
145​
146 // Handle error boundary
147 if (
148 getHasError({
149 result,
150 errorResetBoundary,
151 throwOnError: defaultedOptions.throwOnError,
152 query,
153 suspense: defaultedOptions.suspense,
154 })
155 ) {
156 throw result.error
157 }
158​
159 // Handle result property usage tracking
160 return !defaultedOptions.notifyOnChangeProps
161 ? observer.trackResult(result)
162 : result