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

useBaseQuery.ts

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