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

useBaseQuery.ts

389 lines11.3 KB

1// Had to disable the lint rule because isServer type is defined as false
2// in solid-js/web package. I'll create a GitHub issue with them to see
3// why that happens.
4import { hydrate, notifyManager, shouldThrowError } from '@tanstack/query-core'
5import { isServer } from 'solid-js/web'
6import {
7 createComputed,
8 createMemo,
9 createResource,
10 createSignal,
11 on,
12 onCleanup,
13} from 'solid-js'
14import { createStore, reconcile, unwrap } from 'solid-js/store'
15import { useQueryClient } from './QueryClientProvider'
16import { useIsRestoring } from './isRestoring'
17import type { UseBaseQueryOptions } from './types'
18import type { Accessor, Signal } from 'solid-js'
19import type { QueryClient } from './QueryClient'
20import type {
21 Query,
22 QueryKey,
23 QueryObserver,
24 QueryObserverResult,
25} from '@tanstack/query-core'
26​
27function reconcileFn<TData, TError>(
28 store: QueryObserverResult<TData, TError>,
29 result: QueryObserverResult<TData, TError>,
30 reconcileOption:
31 | string
32 | false
33 | ((oldData: TData | undefined, newData: TData) => TData),
34 queryHash?: string,
35): QueryObserverResult<TData, TError> {
36 if (reconcileOption === false) return result
37 if (typeof reconcileOption === 'function') {
38 const newData = reconcileOption(store.data, result.data as TData)
39 return { ...result, data: newData } as typeof result
40 }
41 let data = result.data
42 if (store.data === undefined) {
43 try {
44 data = structuredClone(data)
45 } catch (error) {
46 if (process.env.NODE_ENV !== 'production') {
47 if (error instanceof Error) {
48 console.warn(
49 `Unable to correctly reconcile data for query key: ${queryHash}. ` +
50 `Possibly because the query data contains data structures that aren't supported ` +
51 `by the 'structuredClone' algorithm. Consider using a callback function instead ` +
52 `to manage the reconciliation manually.\n\n Error Received: ${error.name} - ${error.message}`,
53 )
54 }
55 }
56 }
57 }
58 const newData = reconcile(data, { key: reconcileOption })(store.data)
59 return { ...result, data: newData } as typeof result
61​
62/**
63 * Solid's `onHydrated` functionality will silently "fail" (hydrate with an empty object)
64 * if the resource data is not serializable.
65 */
66const hydratableObserverResult = <
67 TQueryFnData,
68 TError,
69 TData,
70 TQueryKey extends QueryKey,
71 TDataHydratable,
72>(
73 query: Query<TQueryFnData, TError, TData, TQueryKey>,
74 result: QueryObserverResult<TDataHydratable, TError>,
75) => {
76 if (!isServer) return result
77 const obj: any = {
78 ...unwrap(result),
79 // During SSR, functions cannot be serialized, so we need to remove them
80 // This is safe because we will add these functions back when the query is hydrated
81 refetch: undefined,
82 }
83​
84 // If the query is an infinite query, we need to remove additional properties
85 if ('fetchNextPage' in result) {
86 obj.fetchNextPage = undefined
87 obj.fetchPreviousPage = undefined
88 }
89​
90 // We will also attach the dehydrated state of the query to the result
91 // This will be removed on client after hydration
92 obj.hydrationData = {
93 state: query.state,
94 queryKey: query.queryKey,
95 queryHash: query.queryHash,
96 ...(query.meta && { meta: query.meta }),
97 }
98​
99 return obj
101​
102// Base Query Function that is used to create the query.
103export function useBaseQuery<
104 TQueryFnData,
105 TError,
106 TData,
107 TQueryData,
108 TQueryKey extends QueryKey,
109>(
110 options: Accessor<
111 UseBaseQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>
112 >,
113 Observer: typeof QueryObserver,
114 queryClient?: Accessor<QueryClient>,
115) {
116 type ResourceData = QueryObserverResult<TData, TError>
117​
118 const client = createMemo(() => useQueryClient(queryClient?.()))
119 const isRestoring = useIsRestoring()
120 // There are times when we run a query on the server but the resource is never read
121 // This could lead to times when the queryObserver is unsubscribed before the resource has loaded
122 // Causing a time out error. To prevent this we will queue the unsubscribe if the cleanup is called
123 // before the resource has loaded
124 let unsubscribeQueued = false
125​
126 const defaultedOptions = createMemo(() => {
127 const defaultOptions = client().defaultQueryOptions(options())
128 defaultOptions._optimisticResults = isRestoring()
129 ? 'isRestoring'
130 : 'optimistic'
131 defaultOptions.structuralSharing = false
132 if (isServer) {
133 defaultOptions.retry = false
134 defaultOptions.throwOnError = true
135 // Enable prefetch during render for SSR - required for createResource to work
136 // Without this, queries wait for effects which never run on the server
137 defaultOptions.experimental_prefetchInRender = true
138 }
139 return defaultOptions
140 })
141 const initialOptions = defaultedOptions()
142​
143 const [observer, setObserver] = createSignal(
144 new Observer(client(), defaultedOptions()),
145 )
146​
147 let observerResult = observer().getOptimisticResult(defaultedOptions())
148 const [state, setState] =
149 createStore<QueryObserverResult<TData, TError>>(observerResult)
150​
151 const createServerSubscriber = (
152 resolve: (
153 data: ResourceData | PromiseLike<ResourceData | undefined> | undefined,
154 ) => void,
155 reject: (reason?: any) => void,
156 ) => {
157 return observer().subscribe((result) => {
158 notifyManager.batchCalls(() => {
159 const query = observer().getCurrentQuery()
160 const unwrappedResult = hydratableObserverResult(query, result)
161​
162 if (result.data !== undefined && unwrappedResult.isError) {
163 reject(unwrappedResult.error)
164 unsubscribeIfQueued()
165 } else {
166 resolve(unwrappedResult)
167 unsubscribeIfQueued()
168 }
169 })()
170 })
171 }
172​
173 const unsubscribeIfQueued = () => {
174 if (unsubscribeQueued) {
175 unsubscribe?.()
176 unsubscribeQueued = false
177 }
178 }
179​
180 const createClientSubscriber = () => {
181 const obs = observer()
182 return obs.subscribe((result) => {
183 observerResult = result
184 queueMicrotask(() => {
185 if (unsubscribe) {
186 refetch()
187 }
188 })
189 })
190 }
191​
192 function setStateWithReconciliation(res: typeof observerResult) {
193 const opts = observer().options
194 // @ts-expect-error - Reconcile option is not correctly typed internally
195 const reconcileOptions = opts.reconcile
196​
197 setState((store) => {
198 return reconcileFn(
199 store,
200 res,
201 reconcileOptions === undefined ? false : reconcileOptions,
202 opts.queryHash,
203 )
204 })
205 }
206​
207 function createDeepSignal<T>(): Signal<T> {
208 return [
209 () => state,
210 (v: any) => {
211 const unwrapped = unwrap(state)
212 if (typeof v === 'function') {
213 v = v(unwrapped)
214 }
215 // Hydration data exists on first load after SSR,
216 // and should be removed from the observer result
217 if (v?.hydrationData) {
218 const { hydrationData, ...rest } = v
219 v = rest
220 }
221 setStateWithReconciliation(v)
222 },
223 ] as Signal<T>
224 }
225​
226 /**
227 * Unsubscribe is set lazily, so that we can subscribe after hydration when needed.
228 */
229 let unsubscribe: (() => void) | null = null
230​
231 /*
232 Fixes #7275
233 In a few cases, the observer could unmount before the resource is loaded.
234 This leads to Suspense boundaries to be suspended indefinitely.
235 This resolver will be called when the observer is unmounting
236 but the resource is still in a loading state
237 */
238 let resolver: ((value: ResourceData) => void) | null = null
239 const [queryResource, { refetch }] = createResource<ResourceData | undefined>(
240 () => {
241 const obs = observer()
242 return new Promise((resolve, reject) => {
243 resolver = resolve
244 if (isServer) {
245 unsubscribe = createServerSubscriber(resolve, reject)
246 } else if (!unsubscribe && !isRestoring()) {
247 unsubscribe = createClientSubscriber()
248 }
249 obs.updateResult()
250​
251 if (
252 observerResult.isError &&
253 !observerResult.isFetching &&
254 !isRestoring() &&
255 shouldThrowError(obs.options.throwOnError, [
256 observerResult.error,
257 obs.getCurrentQuery(),
258 ])
259 ) {
260 setStateWithReconciliation(observerResult)
261 return reject(observerResult.error)
262 }
263 if (!observerResult.isLoading) {
264 resolver = null
265 return resolve(
266 hydratableObserverResult(obs.getCurrentQuery(), observerResult),
267 )
268 }
269​
270 setStateWithReconciliation(observerResult)
271 })
272 },
273 {
274 storage: createDeepSignal,
275​
276 get deferStream() {
277 return options().deferStream
278 },
279​
280 /**
281 * If this resource was populated on the server (either sync render, or streamed in over time), onHydrated
282 * will be called. This is the point at which we can hydrate the query cache state, and setup the query subscriber.
283 *
284 * Leveraging onHydrated allows us to plug into the async and streaming support that solidjs resources already support.
285 *
286 * Note that this is only invoked on the client, for queries that were originally run on the server.
287 */
288 onHydrated(_k, info) {
289 if (info.value && 'hydrationData' in info.value) {
290 hydrate(client(), {
291 // @ts-expect-error - hydrationData is not correctly typed internally
292 queries: [{ ...info.value.hydrationData }],
293 })
294 }
295​
296 if (unsubscribe) return
297 /**
298 * Do not refetch query on mount if query was fetched on server,
299 * even if `staleTime` is not set.
300 */
301 const newOptions = { ...initialOptions }
302 if (
303 (initialOptions.staleTime || !initialOptions.initialData) &&
304 info.value
305 ) {
306 newOptions.refetchOnMount = false
307 }
308 // Setting the options as an immutable object to prevent
309 // wonky behavior with observer subscriptions
310 observer().setOptions(newOptions)
311 setStateWithReconciliation(observer().getOptimisticResult(newOptions))
312 unsubscribe = createClientSubscriber()
313 },
314 },
315 )
316​
317 createComputed(
318 on(
319 client,
320 (c) => {
321 if (unsubscribe) {
322 unsubscribe()
323 }
324 const newObserver = new Observer(c, defaultedOptions())
325 unsubscribe = createClientSubscriber()
326 setObserver(newObserver)
327 },
328 {
329 defer: true,
330 },
331 ),
332 )
333​
334 createComputed(
335 on(
336 isRestoring,
337 (restoring) => {
338 if (!restoring && !isServer) {
339 refetch()
340 }
341 },
342 { defer: true },
343 ),
344 )
345​
346 onCleanup(() => {
347 if (isServer && queryResource.loading) {
348 unsubscribeQueued = true
349 return
350 }
351 if (unsubscribe) {
352 unsubscribe()
353 unsubscribe = null
354 }
355 if (resolver && !isServer) {
356 resolver(observerResult)
357 resolver = null
358 }
359 })
360​
361 createComputed(
362 on(
363 [observer, defaultedOptions],
364 ([obs, opts]) => {
365 obs.setOptions(opts)
366 setStateWithReconciliation(obs.getOptimisticResult(opts))
367 refetch()
368 },
369 { defer: true },
370 ),
371 )
372​
373 const handler = {
374 get(
375 target: QueryObserverResult<TData, TError>,
376 prop: keyof QueryObserverResult<TData, TError>,
377 ): any {
378 if (prop === 'data') {
379 if (state.data !== undefined) {
380 return queryResource.latest?.data
381 }
382 return queryResource()?.data
383 }
384 return Reflect.get(target, prop)
385 },
386 }
387​
388 return new Proxy(state, handler)