Loading data: load
load(fn, options?) runs an async function for a component and gives you its state as values:
// user.qx
export default function User({ id }) {
let user = load(({ signal }) => fetch(`/api/users/${id}`, { signal }).then((r) => r.json()))
return (
<section>
{if (user.loading)}<p>Loading…</p>
{else if (user.error)}<p>Could not load: {String(user.error)}</p>
{else}<h1>{user.data.name}</h1>
{/if}
</section>
)
}user loadloadcompiles to an import of@qatjs/load:qatjs initlists it inpackage.json; in an app made another way,npm i @qatjs/load.user.loading,user.data,user.errorare reactive values; an error is a value, not a throw.- It refetches when anything
fnread changes (here theidprop), and the superseded request is aborted throughsignal. It is aborted too when the component goes away. - Inside
fn, signals read as values, exactly as inderivedandeffect:state, props, and imported signals such asconst page = query('page', 1)(${page}is the number). Reads after anawaitare not tracked. user.reload()fetches again now (see below).
Reloading: reload()
// orders.qx
export default function Orders() {
let orders = load(() => fetch('/api/orders').then((r) => r.json()))
return (
<section>
<button on:click={() => orders.reload()} disabled={orders.loading}>Refresh</button>
<button on:click={() => orders.reload({ clear: true })}>Start over</button>
{if (orders.loading)}<p>Refreshing…</p>{/if}
<p>{orders.data?.length ?? 0} orders</p>
</section>
)
}orders loadloading is true for the whole of a reload() (retries included), and pending() counts it.
The previous data stays visible until the new result arrives; reload({ clear: true }) clears
it at the start instead. A refetch because something fn read changed sets loading only while
there is no data yet.
Shared data: key
With a key, every load of an equal key (compared structurally: ['user', { id: 1 }] equals
['user', { id: 1 }]) shares one cache entry — one request, the same data everywhere.
The key is reactive, like fn: state, props and imported signals in it are read as values. When
the id prop below changes, the load moves to the entry of ['reviews', <new id>] and fetches
once (aborting the request for the old id); the old entry keeps its data, and every
<ReviewCount> showing the same product shares one request:
// review-count.qx
export default function ReviewCount({ id }) {
let reviews = load(() => fetch(`/api/products/${id}/reviews`).then((r) => r.json()), { key: ['reviews', id] })
return <span>{reviews.data?.length ?? 0} reviews</span>
}reviews load| option | default | meaning |
|---|---|---|
key |
none | share a cache entry; read reactively, written as a value (['reviews', id]) or a function (() => [...]) |
stale |
0 |
ms during which cached data is reused without a request; after that it is shown while it revalidates |
dedupe |
true |
loads of the same key share an in-flight request |
retry |
0 |
retries after a failure: a count (300 ms × 2ⁿ backoff), or { count, delay } (delay × 2ⁿ) |
refetch |
none | refetch every ms, paused while the document is hidden |
refetchOnFocus |
false |
refetch when the window regains focus |
cache |
none | on a server-rendered route: 'static', a duration ('5m') or 'user' — see server rendering |
then |
none | 'user': render the cache value on the server, then load the user's own in the browser |
stream |
deferred | 'critical': the server waits for it before sending the page |
live |
false |
true: the server keeps it current, pushing new data for its key; needs a key (QX-LIVE-KEY) unless an api operation keys it — see live loads |
A shared request is aborted only when its last subscriber is gone.
stale also reaches the service worker of a qatjs compress --pwa
build, which keeps each load's GET response. If you pass signal to fetch, as above, a reload
within stale is answered from the worker's cache, and offline the last response is the answer.
(signal.qatStale carries the value. Without --pwa nothing reads it.)
Optimistic updates: mutate
// reviews.qx
export default function Reviews({ id }) {
let reviews = load(() => api.reviews(id), { key: ['reviews', id] })
const post = (text) => reviews.mutate((list) => [...(list ?? []), { text }], api.addReview(id, text)).catch(() => {})
return <button on:click={() => post('Great')}>Post a review ({reviews.data?.length ?? 0})</button>
}reviews loadmutate(fn) shows fn(data) at once, to every load of the key. With a second argument (a promise
or a function returning one), a rejection rolls back to the previous data, sets error and rejects mutate's own promise
too (catch it, as above, or it is an unhandled rejection); a resolved value other than
undefined becomes the data.
One spinner per page: pending()
// dashboard.qx
import { pending } from '@qatjs/load'
export default function Dashboard() {
const busy = pending() // before the loads below it
let stats = load(() => api.stats())
let feed = load(() => api.feed())
return <main>{if (busy)}<div class="spinner" />{/if}<p>{stats.data?.users} users</p></main>
}stats loadfeed loadpending() is true while any load in the component's subtree — this component and everything it
renders, nested pending() scopes included — is loading. A load that goes away stops counting.
From plain code
import { invalidate, prefetch } from '@qatjs/load'
await prefetch(['reviews', '3'], () => api.reviews('3')) // fill the cache ahead of use
invalidate(['reviews', '3']) // mark stale and refetch for every live load of the keyThe cache is per root
The cache is global by default. provide(LoadCache, createCache()) (from @qatjs/load) gives a tree
its own. The server renderer does this for every request, so one user's data never reaches another
(see server rendering).
A list a page at a time: @qatjs/load/pages
// orders.qx
import { pages } from '@qatjs/load/pages'
import { virtual } from '@qatjs/ui/virtual'
export default function Orders() {
const orders = pages(['orders'], (cursor, { signal }) => api.orders.list({ cursor, signal }))
const v = virtual(orders.items, { size: 48 })
let scroller
mount(() => v.attach(scroller))
// the window near the end: the next page (none while one is on its way)
effect(() => v.last > orders.items.length - 20 && orders.hasNext() && orders.next())
return (
<div ref={scroller} class="list">
<div style:height={v.total + 'px'} style:position="relative">
{for (const o of v)}<div class="row">{o.name}</div>{/for}
</div>
{if (orders.loading)}<p role="status">Loading…</p>{/if}
</div>
)
}fetch(cursor) answers { items, next?, prev? }. The first page is an ordinary load: cached by
its key, rendered on the server and resumed. Pages after it (next()) and before it (prev()) are
added to items, one deep store, so a page arrives as element changes, not as a new list. A virtual
window and a delta-mode chain over items redo only what is new. A new key (or reload()) starts
the list again; a page still on its way from the list before is dropped. Only the first page's
fetch gets the load's signal: a later page gets {}, so it is not aborted with the key or the
component (it is the user's to stop, and its result is dropped if the list started again). A later page that fails rejects its next(); error() is the first page's.
loading is true while any page is on its way. In .qx, loading, data and error read as a
load's do; items is a deep store, read as it is. 400 B.
A store changed at once, undone if refused: @qatjs/load/optimistic
// order.qx
import { optimistic } from '@qatjs/load/optimistic'
export default function Order({ order }) {
const cancel = () =>
optimistic(order, (o) => (o.status = 'Cancelled'), () => api.orders.update({ id: order.id, status: 'Cancelled' }))
.catch(() => toast({ title: 'Not cancelled', kind: 'error' }))
return <button on:click={cancel}>Cancel ({order.status})</button>
}mutate replaces a load's data. optimistic writes into a deep store: a state, a store's field,
or one row of a list. draft writes through a proxy that records each write's inverse. If
commit rejects, exactly those writes are undone, in reverse; a write made meanwhile by someone
else stays. If the response contradicts a value the draft wrote, that is a conflict: the draft is
undone and the server's values are taken. Otherwise the server's values are merged in. Two drafts of
one field in flight at once cannot both be undone correctly, so let one save run at a time (the
explore corpus's 08-optimistic shows the race and this fix). 380 B.
Retries: @qatjs/load/retry
import { retry } from '@qatjs/load/retry'
let orders = load(retry(({ signal }) => api.orders.list({}, { signal }), { count: 4, when: (e) => e.status >= 500 }))
await retry(api.orders.replace, { write: true })({ id, body }) // PUT: retried
await retry(api.orders.create, { write: true })({ body }) // POST: tried once
await retry(() => fetch(url, { method: 'PUT', body }), { write: true, idempotent: true })() // said so: retriedorders loadcount retries (default 3), backoff: 'exponential' (delay × 2ⁿ, from delay, default 300 ms)
or a fixed number of ms, each wait jittered (half to all of it, so many clients do not retry in
step). when(err, attempt) decides per error. The load's signal stops it, even mid-wait. A write
(write: true) is retried only if it is idempotent: idempotent: true, or a qatjs api operation
that is idempotent (GET, PUT, DELETE, or one the document marks x-idempotent: true; each
operation carries .idempotent) passed to retry itself, as above, with its parameters given to
the function retry returns. An arrow carries no mark: a write in one is tried once unless it
says idempotent: true. 389 B.
An app with a TanStack QueryClient: @qatjs/tanstack-query
// main.js
import { QueryClient } from '@tanstack/query-core'
import { queryClient } from '@qatjs/tanstack-query'
queryClient(new QueryClient())// products.qx
import { query } from '@qatjs/tanstack-query'
export default function Products({ page }) {
const products = query(({ signal }) => api.products({ page }, { signal }), { key: ['products', page] })
return <p>{products.loading ? 'Loading…' : `${products.data?.length} products`}</p>
}query() has load's shape (loading, data, error, reload, mutate), and pending() counts
it. Its data lives in the QueryClient, so it is shared with whatever already reads and writes that
client: a React island, queryClient.invalidateQueries(…), TanStack's devtools and persisters.
TanStack's rules apply where the two differ: a query refetches when its key changes, not when what
fn reads changes. In .qx its loading, data and error read as a load's do; in .ts and
.tsx they are called (products.data()).
Which to use. load by default: it is in the first-party 15 kB (14.89 kB by pnpm size), keyed by structural equality, server
rendered and resumed, with pending(), mutate, stale, dedupe. Use @qatjs/tanstack-query when
the app already has a QueryClient that other code shares: a migration from React Query, a React
island beside Qat pages, or TanStack's persisters and devtools. It costs @tanstack/query-core's
client and observer (8.8 kB gzip) plus 1.1 kB.
Against TanStack Query
TanStack Query 5.104 (@tanstack/query-core), its features as its docs list them, against load
and its three entries. "Gap closed" marks what was added after the first comparison.
| Feature | Qat | TanStack Query 5.104 |
|---|---|---|
| a shared cache by key, structural | yes (key) |
yes |
stale-while-revalidate, stale |
yes | yes (staleTime) |
| dedupe | yes | yes |
| refetch on an interval, on focus | yes (refetch, refetchOnFocus) |
yes |
| invalidate, prefetch | yes | yes |
| retry with backoff | yes: retry (count, delay); gap closed: @qatjs/load/retry adds jitter, when, abort mid-wait, writes only when idempotent |
yes (count, delay function; mutations not retried by default) |
| optimistic update of a load's data | yes (mutate, rolled back) |
yes (onMutate, the app rolls back) |
| optimistic update of a store, exact undo | gap closed: @qatjs/load/optimistic (the writes' inverse, a conflict undone) |
no: the app keeps the previous value |
| infinite / cursor queries | gap closed: @qatjs/load/pages (bidirectional, one deep store, a virtual window drives it) |
yes (InfiniteQueryObserver, pages as an array of arrays) |
| a loading flag per subtree | yes (pending()) |
different: useIsFetching counts the whole client |
| server render and resume | yes (the first page too) | yes (dehydrate / hydrate, by hand) |
| abort on unmount | yes | yes (when the function reads the signal) |
| garbage collection of unused entries | different: the cache is per root (per request on the server) | yes (gcTime) |
| persisters (localStorage, IndexedDB) | different: store({ persist }) for state; a load's cache is not persisted |
yes (plugins) |
| devtools | yes (__qat.explain() lists the cache; @qatjs/devtools) |
yes (a panel) |
| offline mutation queue | different: @qatjs/form/offline queues form submissions |
yes (paused mutations) |
| use TanStack's own cache | gap closed: @qatjs/tanstack-query |
— |