Skip to content

Fetching and Freshness

A list can often stay useful while it refreshes, but a confirmation screen may need to wait for the current server response. Query separates these choices from how long a value remains in memory. A freshness deadline determines whether a read may revalidate; stale data is a retained value whose deadline has passed.

Use the shared instance from Getting Started and a stable key. This page uses Profile for the JSON shape { id: number, name: string, role: string } and /profile.json for its URL.

An ordinary read returns a promise for the requested value:

const profile = await query.query<Profile>('/profile.json')

If the key has no cached value, the promise waits for the fetcher. If the value is still valid, Query returns its cached promise without starting another request. If it has expired, Query returns the older cached promise and starts or joins a request in the background. This last behavior is called stale-while-revalidate.

Awaiting a stale read confirms that an older value is available, not that the background request succeeded. Imperative code that needs background updates must subscribe to events; simply awaiting the same old promise again does not turn it into the new value.

Entry at read timeDefault resultFetching
MissingWait for a requestStart or join eligible pending work
Deadline in the futureCached valueNo new request
Deadline reached or passedCached stale valueStart or join revalidation

Fetched values receive a 2,000 ms lifetime by default, measured from successful cache commit. Use an expiration callback to change that lifetime:

const profile = await query.query<Profile>('/profile.json', {
expiration: () => 30_000,
})

This affects the value if this call starts the request that commits it. It does not extend an existing entry on a cache hit. A zero or negative lifetime makes the result immediately eligible for revalidation. Use a finite nonnegative duration for a deliberate useful lifetime; Query does not validate or clamp the callback’s result.

When the next action depends on an up-to-date result, disallow stale data for that read:

const profile = await query.query<Profile>('/profile.json', { stale: false })

If the entry has expired, the returned promise waits for revalidation and rejects if it fails. A still-valid entry is reused. In other words, stale: false does not force a request.

This is a client-side read policy, not a consistency guarantee about a server or database. Authorization and consequential write validation still belong on the server.

A user pressing Refresh usually expects a request even inside the freshness window. Pass fresh: true for that action:

const profile = await query.query<Profile>('/profile.json', { fresh: true })

Every imperative fresh call bypasses cached data and aborts the current same-key request before starting a replacement. It bypasses normal pending-request deduplication too. Two simultaneous fresh calls replace each other; do not scatter fresh imperative reads across consumers that are meant to cooperate.

Aborting affects every caller sharing that key’s pending request. Those callers still need rejection handlers. It does not erase an existing cached value. The cancellation guide explains what happens if the transport ignores the signal. React applies fresh reads to a shared render lifetime instead of replacing the request on each render.

The default fetcher performs fetch(key, { signal }), rejects non-OK responses with Error('Unable to fetch the data: ' + response.statusText), and parses JSON. Fetch failures and JSON parsing errors propagate. It adds no authentication headers, runtime shape validation, retry policy, or timeout.

For a protected JSON endpoint, configure a fetcher where the application owns its credentials. This example uses same-origin cookies and validates the fields it consumes:

import { createQuery } from '@studiolambda/query'
/** Validated representation consumed by the profile screen. */
interface Profile {
readonly id: number
readonly name: string
readonly role: string
}
/** Rejects malformed JSON before it becomes shared application data. */
async function fetchProfile(key: string, { signal }: { readonly signal: AbortSignal }) {
const response = await fetch(key, { signal, credentials: 'same-origin' })
if (!response.ok) throw new Error(`profile request failed: ${response.status}`)
const data: unknown = await response.json()
if (
typeof data !== 'object' || data === null ||
!('id' in data) || typeof data.id !== 'number' ||
!('name' in data) || typeof data.name !== 'string' ||
!('role' in data) || typeof data.role !== 'string'
) {
throw new Error('invalid profile response')
}
return { id: data.id, name: data.name, role: data.role }
}
/** Share this instance only within the intended authenticated scope. */
const query = createQuery({ fetcher: fetchProfile })

Do not treat query.query<Profile>() alone as validation. Its generic is a TypeScript expectation, not a check performed on the response. For authenticated applications, use scope-aware ownership so cached data does not survive into another user’s scope.

If you already have a fetch-compatible transport, defaultFetcher<Profile>(transport) adapts it to the JSON contract above. Import defaultFetcher from @studiolambda/query; supply the transport function explicitly.

Handle failure without discarding useful data

Section titled “Handle failure without discarding useful data”

An awaited cache-miss, blocking, or fresh request rejects on failure. Catch it at the application boundary that can offer recovery. For background failures, subscribe to error before starting work:

const stop = query.subscribe('/profile.json', 'error', (event) => {
console.error('Profile refresh failed:', event.detail)
})

Call stop() when the observer is no longer needed. By default, an owning request failure removes its pending-request entry but preserves the previous cached result. Set removeOnError: true only when retaining that value is inappropriate; it deletes the stored item on the owning failure, but does not itself clear every already-rendered UI.

A failed expiration callback is also a request failure. An obsolete request superseded by a replacement or committed local write cannot delete newer data or emit a completion error. Its own caller can still reject. See mutation races before combining reads and writes.

There is no automatic request at expiration, focus, reconnect, or a polling interval. The application initiates reads; the React guide shows how to own browser event listeners explicitly.