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

useBaseQuery.ts

136 lines4.0 KB

1import { noop, notifyManager } from '@tanstack/query-core'
2import type {
3 QueryClient,
4 QueryKey,
5 QueryObserver,
6 QueryObserverResult,
7} from '@tanstack/query-core'
8import { useCallback, useEffect, useState } from 'preact/hooks'
9​
10import { useIsRestoring } from './IsRestoringProvider'
11import { useQueryClient } from './QueryClientProvider'
12import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'
13import {
14 ensurePreventErrorBoundaryRetry,
15 getHasError,
16 useClearResetErrorBoundary,
17} from './errorBoundaryUtils'
18import {
19 ensureSuspenseTimers,
20 fetchOptimistic,
21 shouldSuspend,
22} from './suspense'
23import type { UseBaseQueryOptions } from './types'
24import { useSyncExternalStore } from './utils'
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<TQueryFnData, TError, TQueryData, TQueryKey>(
59 defaultedOptions.queryHash,
60 )
61​
62 if (process.env.NODE_ENV !== 'production') {
63 if (!defaultedOptions.queryFn) {
64 console.error(
65 `[${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`,
66 )
67 }
68 }
69​
70 // Make sure results are optimistically set in fetching state before subscribing or updating options
71 defaultedOptions._optimisticResults = isRestoring
72 ? 'isRestoring'
73 : 'optimistic'
74​
75 ensureSuspenseTimers(defaultedOptions)
76 ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query)
77​
78 useClearResetErrorBoundary(errorResetBoundary)
79​
80 const [observer] = useState(
81 () =>
82 new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
83 client,
84 defaultedOptions,
85 ),
86 )
87​
88 // note: this must be called before useSyncExternalStore
89 const result = observer.getOptimisticResult(defaultedOptions)
90​
91 const shouldSubscribe = !isRestoring && options.subscribed !== false
92 useSyncExternalStore(
93 useCallback(
94 (onStoreChange) => {
95 const unsubscribe = shouldSubscribe
96 ? observer.subscribe(notifyManager.batchCalls(onStoreChange))
97 : noop
98​
99 // Update result to make sure we did not miss any query updates
100 // between creating the observer and subscribing to it.
101 observer.updateResult()
102​
103 return unsubscribe
104 },
105 [observer, shouldSubscribe],
106 ),
107 () => observer.getCurrentResult(),
108 )
109​
110 useEffect(() => {
111 observer.setOptions(defaultedOptions)
112 }, [defaultedOptions, observer])
113​
114 // Handle suspense
115 if (shouldSuspend(defaultedOptions, result)) {
116 throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
117 }
118​
119 // Handle error boundary
120 if (
121 getHasError({
122 result,
123 errorResetBoundary,
124 throwOnError: defaultedOptions.throwOnError,
125 query,
126 suspense: defaultedOptions.suspense,
127 })
128 ) {
129 throw result.error
130 }
131​
132 // Handle result property usage tracking
133 return !defaultedOptions.notifyOnChangeProps
134 ? observer.trackResult(result)
135 : result