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