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