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

useBaseQuery.ts

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