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