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

useBaseQuery.ts

168 lines5.6 KB

1// `useBaseQuery` β€” the shared core of `useQuery` (and friends), reimplemented on
2// octane's hooks. Mirrors @tanstack/react-query's useBaseQuery: it creates a
3// query Observer, subscribes to it via useSyncExternalStore, and pushes option
4// changes through useEffect. The single compiler-injected slot is split into
5// distinct sub-slots for each internal base hook, the same way the zustand
6// `traditional` binding does.
7import { useCallback, useEffect, useState, useSyncExternalStore } from 'octane'
8import { environmentManager, noop, notifyManager } from '@tanstack/query-core'
9import { resolveClient } from './context'
10import { useIsRestoring } from './isRestoring'
11import { useQueryErrorResetBoundary } from './errorResetBoundary'
12import {
13 ensurePreventErrorBoundaryRetry,
14 ensureSuspenseTimers,
15 fetchOptimistic,
16 getHasError,
17 shouldSuspend,
18 subSlot,
19 useSuspensePromise,
20 willFetch,
21} from './internal'
22​
23export function useBaseQuery(
24 options: any,
25 Observer: any,
26 queryClient: any,
27 slot: symbol | undefined,
28): any {
29 if (process.env.NODE_ENV !== 'production') {
30 if (typeof options !== 'object' || Array.isArray(options)) {
31 throw new Error(
32 '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',
33 )
34 }
35 }
36​
37 const oq = (tag: string) => subSlot(slot, 'oq:' + tag)
38 const client = resolveClient(queryClient)
39 const isRestoring = useIsRestoring()
40 const errorResetBoundary = useQueryErrorResetBoundary()
41 const defaultedOptions = client.defaultQueryOptions(options)
42​
43 ;(client.getDefaultOptions().queries as any)?._experimental_beforeQuery?.(
44 defaultedOptions,
45 )
46​
47 const query = client.getQueryCache().get(defaultedOptions.queryHash)
48​
49 if (process.env.NODE_ENV !== 'production') {
50 if (!defaultedOptions.queryFn) {
51 console.error(
52 `[${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`,
53 )
54 }
55 }
56​
57 // `subscribed: false` makes a passive query (read the cache, never subscribe).
58 // While restoring a persisted client, queries also stay passive.
59 const subscribed = options.subscribed !== false
60 defaultedOptions._optimisticResults = isRestoring
61 ? 'isRestoring'
62 : subscribed
63 ? 'optimistic'
64 : undefined
65​
66 ensureSuspenseTimers(defaultedOptions)
67 ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query)
68 // Clear the reset boundary on mount (so a fresh mount can throw again).
69 useEffect(
70 () => {
71 errorResetBoundary.clearReset()
72 },
73 [errorResetBoundary],
74 oq('clr'),
75 )
76​
77 // Probed BEFORE creating the Observer β€” the constructor can create the entry.
78 const isNewCacheEntry = !client
79 .getQueryCache()
80 .get(defaultedOptions.queryHash)
81​
82 const [observer] = useState(
83 () => new Observer(client, defaultedOptions),
84 oq('obs'),
85 )
86​
87 const result = observer.getOptimisticResult(defaultedOptions)
88​
89 const shouldSubscribe = !isRestoring && subscribed
90 useSyncExternalStore(
91 useCallback(
92 (onStoreChange: () => void) => {
93 const unsubscribe = shouldSubscribe
94 ? observer.subscribe(notifyManager.batchCalls(onStoreChange))
95 : noop
96 observer.updateResult()
97 return unsubscribe
98 },
99 [observer, shouldSubscribe],
100 oq('cb'),
101 ),
102 () => observer.getCurrentResult(),
103 () => observer.getCurrentResult(),
104 oq('uses'),
105 )
106​
107 useEffect(
108 () => {
109 observer.setOptions(defaultedOptions)
110 },
111 [defaultedOptions, observer],
112 oq('eff'),
113 )
114​
115 // Suspend on a promise retained for this query-hook call site. Keeping the
116 // settled promise in the dynamic use() sequence prevents a later sequential
117 // query from taking this query's replay position. fetchOptimistic clears the
118 // reset boundary on error; the replay surfaces that error through the
119 // error-boundary throw below.
120 useSuspensePromise(
121 shouldSuspend(defaultedOptions, result),
122 defaultedOptions.queryHash,
123 () => fetchOptimistic(defaultedOptions, observer, errorResetBoundary),
124 oq('sus'),
125 )
126​
127 // Error boundary: throw so the nearest @try/@catch (or <ErrorBoundary>) handles
128 // it, when the query errored and the options opt into throwing.
129 if (
130 getHasError({
131 result,
132 errorResetBoundary,
133 throwOnError: defaultedOptions.throwOnError,
134 query,
135 suspense: defaultedOptions.suspense,
136 })
137 ) {
138 throw result.error
139 }
140​
141 ;(client.getDefaultOptions().queries as any)?._experimental_afterQuery?.(
142 defaultedOptions,
143 result,
144 )
145​
146 // experimental_prefetchInRender: kick the fetch during render so
147 // `result.promise` settles even if the component unmounts, and finalize the
148 // observer's thenable (via updateResult) when the data lands.
149 if (
150 defaultedOptions.experimental_prefetchInRender &&
151 !environmentManager.isServer() &&
152 willFetch(result, isRestoring)
153 ) {
154 const promise = isNewCacheEntry
155 ? // Fetch immediately on render so `.promise` resolves even on unmount.
156 fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
157 : // Subscribe to the cache promise to finalize the current thenable.
158 query?.promise
159​
160 promise?.catch(noop).finally(() => {
161 observer.updateResult()
162 })
163 }
164​
165 return !defaultedOptions.notifyOnChangeProps
166 ? observer.trackResult(result)
167 : result