Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useBaseQuery.ts

817 lines31.0 KB

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