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

useBaseQuery.ts

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