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

useBaseQuery.ts

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