Open History to see the last commit
1import { hydrate, noop, shouldThrowError } from '@tanstack/query-core'
2import {
3 createMemo,
4 createProjection,
5 createRenderEffect,
6 createSignal,
7 isHydrating,
8 isPending as isValuePending,
9 onCleanup,
10 resolve,
11 runWithOwner,
12 untrack,
13} from 'solid-js'
14import { takeHydrationValue } from '@solidjs/web'
15import { HYDRATION_KEY_PREFIX, useQueryClient } from './QueryClientProvider'
16import { useIsRestoring } from './isRestoring'
17import type { UseBaseQueryOptions, UseBaseQueryResult } from './types'
18import type { Accessor } from 'solid-js'
19import type { QueryClient } from './QueryClient'
20import type {
21 DefaultedQueryObserverOptions,
22 Query,
23 QueryKey,
24 QueryObserver,
25 QueryObserverResult,
26 QueryState,
27} from '@tanstack/query-core'
28β
29const isServer = typeof window === 'undefined'
30β
31/**
32 * A read of a pending-idle query (disabled, or reset with nothing in flight)
33 * has no value and nothing to wait on. Parking the reader on a promise that
34 * never resolves suspends it into the nearest `<Loading>` boundary until the
35 * query actually starts fetching (enabling it, a refetch, a cache write) β
36 * at which point the version bump re-runs the compute and the superseded
37 * in-flight is ignored by the engine.
38 */
39const NEVER: Promise<never> = new Promise(noop)
40β
41/** The scalar half of QueryState β `data` flows through the async node, not here. */
42type MetaState = Omit<QueryState<unknown, unknown>, 'data' | 'fetchMeta'>
43β
44/**
45 * A cache entry in Solid's hydration registry, serialized by the
46 * provider under `sq:<queryHash>` β see `serializeCacheOnServer`.
47 */
48interface HydratedEntry {
49 data: unknown
50 t: number
51}
52β
53/**
54 * Copies the scalar fields of a query's state, leaving out `data` and `fetchMeta`.
55 * @param state - The query state to copy from.
56 * @returns The scalar metadata.
57 */
58function metaFrom(state: QueryState<any, any>): MetaState {
59 return {
60 dataUpdateCount: state.dataUpdateCount,
61 dataUpdatedAt: state.dataUpdatedAt,
62 error: state.error,
63 errorUpdateCount: state.errorUpdateCount,
64 errorUpdatedAt: state.errorUpdatedAt,
65 fetchFailureCount: state.fetchFailureCount,
66 fetchFailureReason: state.fetchFailureReason,
67 fetchStatus: state.fetchStatus,
68 isInvalidated: state.isInvalidated,
69 status: state.status,
70 }
71}
72β
73/**
74 * Internal seam: everything the read layer builds, for hooks that extend
75 * the base result (`useInfiniteQuery` pagers ride the same entry).
76 */
77interface BaseQueryLayer<
78 TQueryFnData,
79 TError,
80 TData,
81 TQueryData,
82 TQueryKey extends QueryKey,
83> {
84 result: UseBaseQueryResult<TData, TError>
85 observer: QueryObserver<TQueryFnData, TError, TData, TQueryData, TQueryKey>
86 /** Version-tracked: reading it subscribes to this query's cache events. */
87 query: () => Query<TQueryFnData, TError, TQueryData, TQueryKey>
88 defaultedOptions: Accessor<ReturnType<QueryClient['defaultQueryOptions']>>
89 isFetching: () => boolean
90 status: () => 'pending' | 'error' | 'success'
91}
92β
93/**
94 * Base Query Function that is used to create the query.
95 * @param options - A function that returns the query options.
96 * @param Observer - The observer class from query-core (`QueryObserver` or
97 * `InfiniteQueryObserver`).
98 * @param queryClient - A function that returns a custom `QueryClient`. Otherwise, the one from the
99 * nearest context is used.
100 * @returns The reactive query result.
101 */
102export function useBaseQuery<
103 TQueryFnData,
104 TError,
105 TData,
106 TQueryData,
107 TQueryKey extends QueryKey,
108>(
109 options: Accessor<
110 UseBaseQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>
111 >,
112 Observer: typeof QueryObserver,
113 queryClient?: Accessor<QueryClient>,
114): UseBaseQueryResult<TData, TError> {
115 return useBaseQueryLayer(options, Observer, queryClient).result
116}
117β
118/**
119 * Builds the read layer behind `useBaseQuery` and exposes its internals to hooks that extend it.
120 * @param options - A function that returns the query options.
121 * @param Observer - The observer class from query-core (`QueryObserver` or
122 * `InfiniteQueryObserver`).
123 * @param queryClient - A function that returns a custom `QueryClient`. Otherwise, the one from the
124 * nearest context is used.
125 * @returns The query result, with the observer, the version-tracked query accessor, the defaulted
126 * options, and the `isFetching` and `status` accessors.
127 */
128export function useBaseQueryLayer<
129 TQueryFnData,
130 TError,
131 TData,
132 TQueryData,
133 TQueryKey extends QueryKey,
134>(
135 options: Accessor<
136 UseBaseQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>
137 >,
138 Observer: typeof QueryObserver,
139 queryClient?: Accessor<QueryClient>,
140): BaseQueryLayer<TQueryFnData, TError, TData, TQueryData, TQueryKey> {
141 const client = createMemo(() => useQueryClient(queryClient?.()))
142 const isRestoring = useIsRestoring()
143β
144 /**
145 * The most recently computed hash, updated on every options compute β
146 * including holds, where the memo's committed face still serves the old
147 * options. The cache-event filter below must match both: on a key switch
148 * the new key's fetch settles *before* the hold commits, so filtering by
149 * the committed hash alone drops that settle event and nothing downstream
150 * (data recompute, meta projection) ever learns the fetch finished.
151 */
152 let latestHash: string | undefined
153 let latestOptions:
154 | DefaultedQueryObserverOptions<
155 TQueryFnData,
156 TError,
157 TData,
158 TQueryData,
159 TQueryKey
160 >
161 | undefined
162 const defaultedOptions = createMemo(() => {
163 const defaulted = client().defaultQueryOptions(options())
164 defaulted._optimisticResults = isRestoring() ? 'isRestoring' : 'optimistic'
165 if (isServer) {
166 defaulted.retry = false
167 defaulted.throwOnError = true
168 }
169 latestHash = defaulted.queryHash
170 latestOptions = defaulted
171 return defaulted
172 })
173β
174 /**
175 * The observer is a lifecycle/policy engine only. Registering it pins the
176 * query against garbage collection, engages mount-fetch policy
177 * (`shouldFetchOnMount`), schedules `refetchInterval`, and gates
178 * focus/reconnect refetches β all of which live behind observer
179 * registration in query-core. Reactivity never touches its notifications
180 * or result objects: the listener is a noop, and the reactive layer below
181 * derives everything from cache events and fetch promises.
182 *
183 * `let`, not `const`: a reactive `queryClient` accessor can swap clients
184 * mid-life, and the observer must be rebuilt against the new client (see
185 * `syncClient` below).
186 */
187 let observer = untrack(() => new Observer(client(), defaultedOptions()))
188 // Fetching and refetching can advance observer.options during a hold.
189 let lastAppliedHash = observer.options.queryHash
190β
191 createRenderEffect(
192 () => defaultedOptions(),
193 (opts) => {
194 lastAppliedHash = opts.queryHash
195 observer.setOptions(opts)
196 },
197 )
198β
199 /**
200 * Solid's own "this component is being hydrated" answer, captured at
201 * setup. Always false on the server.
202 */
203 const hydratedMount = isHydrating()
204β
205 /**
206 * One version signal per hook, bumped by cache events for this query hash.
207 * This is the entire subscription model: any state transition on the query
208 * (fetch dispatch, settle, invalidation, `setQueryData`, removal) re-runs
209 * the derived reads below, which pull fresh state/promises from the cache.
210 *
211 * `ownedWrite`: a compute that reads through `query()` can itself create
212 * the cache entry (`cache.build` β synchronous 'added' event β this
213 * write), so the first bump can land inside whatever computation pulled
214 * the entry into existence. This is channel-owned state, not that
215 * computation's own β the same pattern as the router's per-key version
216 * signals.
217 */
218 const [version, setVersion] = createSignal(0, { ownedWrite: true })
219 /**
220 * Whether this hook's serialized data entry has been applied to the
221 * cache (or was determined not to exist). Non-hydrated mounts are born
222 * primed. Gates the pull-model fetch: hydration's takeover recompute can
223 * run against a cache the priming hasn't reached yet, and fetching there
224 * would race data the stream already delivered. Created on both sides
225 * (unread on the server) for hydration id parity.
226 */
227 const [primed, setPrimed] = createSignal(!hydratedMount, {
228 ownedWrite: true,
229 })
230 const onCacheEvent = (event: { query: { queryHash: string } }) => {
231 // Match the last hash applied by the render effect OR the latest
232 // computed one without reading a potentially held memo.
233 if (
234 event.query.queryHash === lastAppliedHash ||
235 event.query.queryHash === latestHash
236 ) {
237 setVersion((v) => v + 1)
238 }
239 }
240β
241 let observerSub: (() => void) | null = null
242 let cacheSub: (() => void) | null = null
243 let disposed = false
244 /**
245 * Set once the mount flow decides the observer should be live β a client
246 * swap re-attaches the rebuilt observer iff its predecessor was attached.
247 */
248 let shouldAttach = false
249 let activeClient = untrack(client)
250 /**
251 * The entry this hook last read at its current hash, and the fallback for
252 * `query()` when the cache no longer holds that hash. Removal is the case
253 * that needs it: `removeQueries()` (or `clear()`) fires 'removed' for a
254 * hash this hook is mounted on, which bumps `version` and re-runs every
255 * derived read, and a plain `build()` there would re-create the entry the
256 * caller just removed. That resurrection is not passive, since the 'added'
257 * entry also re-points the still-live observer, whose mount-fetch policy
258 * then refetches and repopulates the key, contrary to `removeQueries`
259 * being documented to remove entries instead of refetching them.
260 *
261 * The removed instance keeps its final state, so reads hold their last
262 * value until options change or a real entry returns (`setQueryData`, a
263 * refetch, a later mount). That is what the other adapters do: a React
264 * observer keeps rendering the removed query's last result while the
265 * cache stays empty.
266 *
267 * Cleared on a client swap, below: the fallback is only meaningful for the
268 * cache it was read from.
269 */
270 let lastQuery: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined
271β
272 const attach = () => {
273 if (!disposed && !observerSub && !untrack(isRestoring)) {
274 shouldAttach = true
275 observerSub = observer.subscribe(noop)
276 }
277 }
278β
279 /**
280 * Idempotent client re-pointing, called from the tracked `query()` read
281 * (which every derived compute goes through) rather than a dedicated
282 * watcher node β hydration id assignment is positional, so a client-only
283 * effect here would shift every downstream id. On a swap the version
284 * subscription moves to the new cache and the observer is rebuilt against
285 * the new client, so policy fetches and cache events both follow the
286 * client the hook is actually reading.
287 * @param c - The `QueryClient` the hook currently resolves to.
288 */
289 const syncClient = (c: QueryClient) => {
290 if (isServer || c === activeClient) return
291 activeClient = c
292 lastQuery = undefined
293 cacheSub?.()
294 cacheSub = c.getQueryCache().subscribe(onCacheEvent)
295 observerSub?.()
296 observerSub = null
297 observer = new Observer(c, untrack(defaultedOptions))
298 if (shouldAttach && !disposed && !untrack(isRestoring)) {
299 observerSub = observer.subscribe(noop)
300 }
301 }
302β
303 /**
304 * Hydration priming β content-addressed, the Solid Router `query()`
305 * pattern. The provider serialized every query this request touched
306 * into Solid's hydration registry under `sq:<queryHash>` (raw pre-select
307 * data plus `dataUpdatedAt`); here the hook looks its hash up directly
308 * and reconstructs the cache entry through query-core `hydrate()`, so
309 * staleness policy stays honest. Content addressing means coverage is
310 * the CACHE's, not the rendered tree's: prefetched-never-rendered
311 * queries transfer, shared keys prime from whichever hook consumes the
312 * entry first, and β like the router β the registry can still be
313 * consulted past hydration end, so a component mounted long after (lazy route,
314 * post-hydration navigation) still adopts the server's payload instead
315 * of refetching. Entries are consumed one-shot (deleted on load): once
316 * the cache owns the data, a stale registry payload must never shadow
317 * it.
318 *
319 * Ordering matters twice over. The observer attaches only after priming
320 * resolves (on hydrated mounts via `primeAndAttach`; on later mounts by
321 * priming HERE, before the attach render effect below even exists β
322 * its effect half runs synchronously inside an active flush, and mount
323 * policy against a still-cold cache would refetch data the registry
324 * already holds). Settled entries prime synchronously at setup;
325 * streamed entries prime when their chunk lands, per query, so early
326 * components go live while later boundaries still stream. No entry
327 * (placeholder queries serialize nothing; SSR errors adopt at their
328 * boundary) attaches immediately and lets mount policy decide.
329 * @param entry - The hydration registry entry for this query's hash, if one exists.
330 */
331 const prime = (entry?: Partial<HydratedEntry> | null) => {
332 if (entry != null && typeof entry === 'object' && (entry.t ?? 0) > 0) {
333 const c = untrack(client)
334 const opts = untrack(defaultedOptions)
335 // Escape the setup/owned scope: hydrate() synchronously notifies
336 // cache subscribers, which may write into other hooks' stores.
337 runWithOwner(null, () =>
338 hydrate(c, {
339 mutations: [],
340 queries: [
341 {
342 queryKey: opts.queryKey,
343 queryHash: opts.queryHash,
344 dehydratedAt: entry.t,
345 ...(opts.meta && { meta: opts.meta }),
346 ...((opts as { _type?: string })._type && {
347 queryType: (opts as { _type?: string })._type,
348 }),
349 state: {
350 data: entry.data,
351 dataUpdatedAt: entry.t,
352 dataUpdateCount: 1,
353 error: null,
354 errorUpdateCount: 0,
355 errorUpdatedAt: 0,
356 fetchFailureCount: 0,
357 fetchFailureReason: null,
358 fetchMeta: null,
359 isInvalidated: false,
360 status: 'success',
361 fetchStatus: 'idle',
362 },
363 },
364 ],
365 } as Parameters<typeof hydrate>[1]),
366 )
367 }
368 }
369β
370 if (!isServer) {
371 cacheSub = activeClient.getQueryCache().subscribe(onCacheEvent)
372 const registryKey =
373 HYDRATION_KEY_PREFIX + untrack(defaultedOptions).queryHash
374 const primeAndAttach = (entry?: Partial<HydratedEntry> | null) => {
375 prime(entry)
376 setPrimed(true)
377 attach()
378 }
379 const settle = hydratedMount ? primeAndAttach : prime
380 const entry = takeHydrationValue<Partial<HydratedEntry> | null>(registryKey)
381 if (entry?.status === 'resolved') settle(entry.value)
382 else if (entry?.status === 'rejected') settle()
383 else if (entry?.status === 'pending')
384 entry.promise.then(settle, () => settle())
385 else if (hydratedMount) primeAndAttach()
386 if (!hydratedMount) {
387 createRenderEffect(
388 () => isRestoring(),
389 (restoring) => {
390 if (!restoring) attach()
391 },
392 )
393 }
394 onCleanup(() => {
395 disposed = true
396 observerSub?.()
397 observerSub = null
398 cacheSub?.()
399 cacheSub = null
400 })
401 }
402β
403 /**
404 * The cache entry for the current options, without the `version` read β
405 * for the setup-time snapshots below (`metaProjection`'s seed,
406 * `mountedAt`), which run in whatever computation is instantiating this
407 * component. Under hydration that matters: priming bumps `version`
408 * during setup, and Solid holds a write made during the hydration pass β
409 * a computation in the pass that reads the written signal, tracked or
410 * not, is served the pre-write snapshot and replays at release. For the
411 * hook's own derived nodes that replay is the takeover. For the
412 * instantiating computation (a boundary's children, a `<Show>` branch)
413 * it is a remount: the hydrated component is disposed and re-created as
414 * a client render, and the server value stops holding the DOM. So the
415 * snapshots read the cache, never the signal.
416 * @returns The cache entry for the current options.
417 */
418 const lookupQuery = (): Query<
419 TQueryFnData,
420 TError,
421 TQueryData,
422 TQueryKey
423 > => {
424 const c = client()
425 syncClient(c)
426 const cache = c.getQueryCache()
427 const opts = defaultedOptions()
428 const existing = cache.get<TQueryFnData, TError, TQueryData, TQueryKey>(
429 opts.queryHash,
430 )
431 if (existing) return (lastQuery = existing)
432 if (lastQuery?.queryHash === opts.queryHash) return lastQuery
433 return (lastQuery = cache.build(c, opts as any) as any)
434 }
435 const query = (): Query<TQueryFnData, TError, TQueryData, TQueryKey> => {
436 version()
437 return lookupQuery()
438 }
439β
440 const isEnabled = () => {
441 const opts = defaultedOptions()
442 const enabled =
443 typeof opts.enabled === 'function'
444 ? (opts.enabled as (q: any) => boolean)(untrack(query))
445 : opts.enabled
446 return enabled !== false
447 }
448β
449 const resolvePlaceholder = (
450 opts: ReturnType<typeof defaultedOptions>,
451 ): TQueryData | undefined => {
452 const placeholder = opts.placeholderData
453 if (placeholder === undefined) return undefined
454 // The function form receives previous data/query in React Query as a
455 // `keepPreviousData` vehicle. Solid 2 holds the previous committed value
456 // natively while a new promise is pending, so previous-data plumbing is
457 // unnecessary here; a function placeholder computes from nothing.
458 return typeof placeholder === 'function'
459 ? (placeholder as () => TQueryData | undefined)()
460 : placeholder
461 }
462β
463 /**
464 * The data compute. It returns either the settled `{ value }` root or a
465 * promise of it β the engine does the rest: pending reads suspend into
466 * `<Loading>` (holding the previous committed value on refetch),
467 * rejections surface to `<Errored>`, transitions hold commits until
468 * in-flight answers land, and on the server the settled value serializes
469 * for hydration adoption on the client.
470 */
471 // Stable promise identity across recomputes: mid-flight version bumps
472 // (fetch dispatch, observer updates) re-run the data compute while the
473 // same underlying fetch is pending. Chaining a fresh `.then` each time
474 // would hand the engine a new pending promise per recompute β the node
475 // keeps restarting its pending tracking and the settle can be missed
476 // (observed as `isPending` probes stuck true after the fetch lands).
477 let chained: {
478 base: Promise<unknown>
479 select: unknown
480 value: Promise<{ value: TData }>
481 } | null = null
482 // The raw cache data behind the last value this hook served. `computeData`
483 // only receives the previous *selected* value, so it cannot tell a fresh
484 // cache write apart from the value it already committed by comparing
485 // `state.data` to `prev` β with a `select`, those are different shapes and
486 // the comparison would almost never match, silently dropping the refetch
487 // hold for every selected query. Tracking the raw data instead keeps the
488 // hold intact: an ordinary refetch writes nothing, so the raw reference
489 // is unchanged and the node keeps waiting on the fetch promise.
490 let lastServedData: unknown = undefined
491 const chainOnce = (
492 base: Promise<any>,
493 select: unknown,
494 wrap: (d: any) => { value: TData },
495 ): Promise<{ value: TData }> => {
496 if (chained?.base !== base || chained.select !== select) {
497 chained = { base, select, value: base.then(wrap) }
498 }
499 return chained.value
500 }
501β
502 const computeData = (
503 prev?: TData,
504 ): { value: TData } | Promise<{ value: TData }> => {
505 const opts = defaultedOptions()
506 const q = query()
507 const state = q.state
508 const select = opts.select
509 const wrap = (d: any): { value: TData } => {
510 const value = select ? select(d as TQueryData) : (d as TData)
511 lastServedData = d
512 return { value }
513 }
514β
515 // Placeholder: show immediately instead of suspending while the first
516 // fetch runs. When the fetch lands the version bump swaps in real data.
517 if (state.data === undefined && state.status === 'pending') {
518 const placeholder = resolvePlaceholder(opts)
519 if (placeholder !== undefined) return wrap(placeholder)
520 }
521β
522 // A fetch in flight (including paused-offline with a retryer attached):
523 // hand the engine the promise. First load suspends; refetch holds the
524 // previous committed value and marks the node pending β which is what
525 // lets a mutation's invalidations hold its settle transition until
526 // fresh data lands.
527 //
528 // Exception: a FIRST compute that already has a value to show
529 // (initialData, hydrated or shared cache data with a mount refetch in
530 // flight) returns the value β suspending would have nothing committed
531 // to hold, blanking the UI on mount. The refetch stays observable via
532 // fetchStatus; the settle lands through the next version bump.
533 if (state.fetchStatus !== 'idle') {
534 if (state.data === undefined || prev !== undefined) {
535 // A cache write landed while this fetch was in flight β a streamed
536 // chunk, or a setQueryData during a refetch. The cache holds newer
537 // data than the value this node committed, so serve it instead of
538 // waiting on the fetch promise, which only resolves when the whole
539 // stream ends. An ordinary refetch writes nothing, so the raw
540 // reference is unchanged and the hold below still applies.
541 if (state.data !== undefined && state.data !== lastServedData) {
542 return wrap(state.data)
543 }
544 const promise = q.promise
545 if (promise) return chainOnce(promise, select, wrap)
546 }
547 }
548β
549 if (state.status === 'error') {
550 // No stale value to serve means the read cannot produce TData β the
551 // rejection surfaces through the graph to the nearest <Errored>.
552 // With stale data present, throw only if throwOnError opts in.
553 if (
554 state.data === undefined ||
555 shouldThrowError(opts.throwOnError as any, [
556 state.error as any,
557 q as any,
558 ])
559 ) {
560 throw state.error
561 }
562 }
563β
564 if (state.data !== undefined) return wrap(state.data)
565β
566 // Pending-idle: nothing in flight, nothing cached. If the query is
567 // enabled, the tracked read itself starts the fetch (the router
568 // `query()` model β reads pull the async). This is not just the server
569 // path: on the client it is what revives a query whose enabling change
570 // arrives while the subtree is parked under a suspended boundary β
571 // parked boundaries hold effects, so the observer's option-driven fetch
572 // can never fire there, but computes still re-run. `q.fetch` dedupes
573 // against any fetch the observer already started.
574 if (isEnabled()) {
575 /**
576 * Never start a fetch inside the hydration window. Adoption
577 * trace-runs this compute even on a hit (solid mocks `fetch` there,
578 * but a TanStack fetch is invisible to that mock) β a query fetching
579 * here would wedge on hydration's Promise mock inside its queryFn
580 * and then swallow every later legitimate refetch through retryer
581 * dedupe. During hydration the value comes from adoption or node
582 * priming; if a fetch is genuinely needed, the post-priming observer
583 * attach issues it outside the window.
584 */
585 if (isHydrating()) {
586 return NEVER
587 }
588 /**
589 * Same discipline until this hook's serialized node entry has primed
590 * the cache (or was found absent): the takeover recompute at
591 * hydration end can land before a streamed entry does, and fetching
592 * against the still-empty cache would race data the stream already
593 * carries. The read is tracked β priming resolves through
594 * `setPrimed`, re-running this compute, and an entry-less query
595 * falls through to a normal fetch here.
596 */
597 if (!primed()) {
598 return NEVER
599 }
600 /**
601 * Same discipline while a persister is restoring: the restored value
602 * is about to land in the cache, so pulling a fetch now would race
603 * it. The read is tracked β `isRestoring` flipping false re-runs
604 * this compute (and the deferred observer attach engages mount
605 * policy), so the fetch fires then if the restore left a gap.
606 */
607 if (isRestoring()) {
608 return NEVER
609 }
610 /**
611 * Sync observer policy before pulling. Under a suspended boundary
612 * the options render effect is deferred, so on an enabled flip or
613 * key change this compute runs first and the effect only lands
614 * after the revival fetch settles β at which point a "changed"
615 * options diff against now-stale data would issue a redundant
616 * policy refetch. Syncing here means any policy fetch starts now
617 * (and `q.fetch` dedupes into it), and the deferred effect later
618 * sees the identical options object β a no-op diff.
619 */
620 if (!isServer) observer.setOptions(opts)
621 return chainOnce(q.fetch(opts), select, wrap)
622 }
623 /**
624 * Disabled, with nothing cached. The three guards above are all
625 * unreachable on the server, but this one is not, and parking here has
626 * no server meaning: the render has to finish, and nothing will enable
627 * the query or write the cache before it does. So commit the idle
628 * value β 'pending' with no data IS a disabled query's settled SSR
629 * truth, which is the contract `serverMeta` already honors by not
630 * tying its read to this node while disabled, and it is the state the
631 * client hydrates to. Committed rather than passed through `wrap`:
632 * `select` must not be invoked on absent data.
633 */
634 if (isServer) return { value: undefined as TData }
635 return NEVER
636 }
637β
638 /**
639 * THE data node: one projection, identical on both sides β the router
640 * "feed `query()` into `createProjection`" shape. The derive asks the
641 * cache for the answer (`computeData`) and the engine owns everything
642 * else: the server runs the derive, waits, and serializes the settled
643 * store under this node's id (`deferStream` holds the flush); pending
644 * reads suspend into `<Loading>`; a hydrating client adopts the
645 * serialized value and re-derives once hydration hands over; and every
646 * landing β refetch, invalidation, placeholder upgrade β auto-reconciles
647 * into the existing proxy graph (keyed by `reconcile`, default `'id'`),
648 * so deep reads are fine-grained and item identity survives fetches.
649 *
650 * The root wrapper exists because store roots must be objects β
651 * primitive data rides the `value` leaf as a plain signal read. The
652 * draft's committed `value` doubles as the previous-data signal for the
653 * first-paint exception in `computeData`.
654 *
655 * Default ('server') hydration semantics: the serialized value owns the
656 * node while it hydrates. Outside every still-pending streamed boundary,
657 * a cache write commits immediately. Under a pending boundary it waits
658 * for that boundary to resume, which hydrates against the server
659 * snapshot.
660 */
661 const dataStore = createProjection<{ value: TData }>(
662 (draft) => computeData(draft.value),
663 {} as { value: TData },
664 {
665 key: untrack(() => options().reconcile),
666 deferStream: untrack(() => options().deferStream),
667 },
668 )
669 const data = () => dataStore.value
670β
671 /**
672 * Scalar result metadata.
673 *
674 * Client: a projection reconciled per-field from query state on every
675 * cache event, so each field is its own fine-grained signal β a component
676 * reading only `isFetching` re-runs on fetchStatus flips, not on every
677 * state transition.
678 *
679 * Server: boundaries guarantee that only settled state serializes, and
680 * meta must honor the same contract (solid's own `isPending` suspends
681 * rather than ever serialize `true`). A projection cannot: its compute
682 * runs once at setup and never re-pulls, freezing an in-flight snapshot
683 * ('pending'/'fetching') into HTML that the hydrating client β reading
684 * the primed, settled cache β contradicts. So on the server every meta
685 * read pulls live query state, and while the entry is unsettled (pending
686 * with a fetch in flight, or one it can start) the read ties itself to the data
687 * node, which throws the pending read and holds the boundary until
688 * settle. A disabled pending query is served as-is: 'pending' IS its
689 * settled SSR truth, and the client hydrates the identical state.
690 * @returns The scalar metadata read live from the query's state.
691 */
692 const serverMeta = (): MetaState => {
693 if (query().state.status === 'pending' && isEnabled()) data()
694 return metaFrom(query().state)
695 }
696 /**
697 * Created on BOTH sides even though the server never reads it: hydration
698 * id assignment is positional, so every reactive node a hook creates on
699 * the client must have a server counterpart (and vice versa) or every id
700 * downstream shifts and hydration key-misses the whole subtree.
701 */
702 const metaProjection = createProjection<MetaState>(
703 (draft) => {
704 Object.assign(draft, metaFrom(query().state))
705 },
706 untrack(() => metaFrom(lookupQuery().state)),
707 )
708 const meta = isServer
709 ? new Proxy({} as MetaState, {
710 get: (_, key) => serverMeta()[key as keyof MetaState],
711 })
712 : metaProjection
713β
714 /**
715 * Server: read live counts instead of a setup snapshot β "mount" resolves
716 * post-settle there, so `isFetchedAfterMount` serializes `false`, which is
717 * exactly what the hydrating client computes (its mount snapshot equals
718 * the hydrated counts).
719 */
720 const mountedAt = isServer
721 ? {
722 get dataUpdateCount() {
723 return untrack(query).state.dataUpdateCount
724 },
725 get errorUpdateCount() {
726 return untrack(query).state.errorUpdateCount
727 },
728 }
729 : untrack(() => {
730 const state = lookupQuery().state
731 return {
732 dataUpdateCount: state.dataUpdateCount,
733 errorUpdateCount: state.errorUpdateCount,
734 }
735 })
736β
737 const hasPlaceholder = () =>
738 meta.status === 'pending' &&
739 untrack(() => resolvePlaceholder(defaultedOptions())) !== undefined
740 const status = () => (hasPlaceholder() ? 'success' : meta.status)
741 const isPending = () => status() === 'pending'
742 /**
743 * A refetch of settled data is a transition: the state write that flips
744 * `fetchStatus` to 'fetching' is held in the same batch as the pending
745 * data node, so the committed meta channel cannot show it mid-hold β by
746 * design, held updates commit atomically. The observable channel for
747 * "a new answer is in flight" during a hold is core's pending probe.
748 * The committed `fetchStatus` covers the first load (where the probe
749 * would see an uninitialized node) and untracked/imperative reads.
750 * @returns `true` while a fetch for this query is in flight.
751 */
752 const isFetching = () =>
753 meta.fetchStatus === 'fetching' || isValuePending(() => data())
754 const isError = () => status() === 'error'
755 const isStale = () => {
756 const opts = defaultedOptions()
757 const q = untrack(query)
758 const staleTime =
759 typeof opts.staleTime === 'function'
760 ? (opts.staleTime as (q: any) => number | 'static')(q)
761 : opts.staleTime
762 version()
763 return q.isStaleByTime(staleTime)
764 }
765β
766 const result = {
767 get data() {
768 return data()
769 },
770 get error() {
771 return meta.error as TError | null
772 },
773 get status() {
774 return status()
775 },
776 get fetchStatus() {
777 return meta.fetchStatus
778 },
779 get isPending() {
780 return isPending()
781 },
782 get isSuccess() {
783 return status() === 'success'
784 },
785 get isError() {
786 return isError()
787 },
788 get isLoading() {
789 return isPending() && isFetching()
790 },
791 get isFetching() {
792 return isFetching()
793 },
794 get isRefetching() {
795 return isFetching() && !isPending()
796 },
797 get isPaused() {
798 return meta.fetchStatus === 'paused'
799 },
800 get isEnabled() {
801 return isEnabled()
802 },
803 get isLoadingError() {
804 return isError() && meta.dataUpdatedAt === 0
805 },
806 get isRefetchError() {
807 return isError() && meta.dataUpdatedAt !== 0
808 },
809 get isPlaceholderData() {
810 return hasPlaceholder()
811 },
812 get isStale() {
813 return isStale()
814 },
815 get isFetched() {
816 return meta.dataUpdateCount > 0 || meta.errorUpdateCount > 0
817 },
818 get isFetchedAfterMount() {
819 return (
820 meta.dataUpdateCount > mountedAt.dataUpdateCount ||
821 meta.errorUpdateCount > mountedAt.errorUpdateCount
822 )
823 },
824 get dataUpdatedAt() {
825 return meta.dataUpdatedAt
826 },
827 get errorUpdatedAt() {
828 return meta.errorUpdatedAt
829 },
830 get failureCount() {
831 return meta.fetchFailureCount
832 },
833 get failureReason() {
834 return meta.fetchFailureReason as TError | null
835 },
836 get errorUpdateCount() {
837 return meta.errorUpdateCount
838 },
839 get promise() {
840 return resolve(() => data())
841 },
842 refetch: ((refetchOptions) => {
843 // A held transition defers the setOptions render effect, so after a
844 // key switch the observer can still carry the previous key's options.
845 // Sync to the latest computed options first: an imperative refetch
846 // targets what the UI is currently asking for, not what last
847 // committed.
848 if (!isServer && latestOptions) {
849 observer.setOptions(latestOptions)
850 }
851 return observer.refetch(refetchOptions)
852 }) as QueryObserverResult<TData, TError>['refetch'],
853 }
854β
855 return {
856 result: result as unknown as UseBaseQueryResult<TData, TError>,
857 observer,
858 query,
859 defaultedOptions,
860 isFetching,
861 status,
862 } as unknown as BaseQueryLayer<
863 TQueryFnData,
864 TError,
865 TData,
866 TQueryData,
867 TQueryKey
868 >
869}