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