Data Fetching

One query cache, shared by everything that reads data. Every key is one entry, and every entry is an async value in the reactive graph: it suspends a <Suspense> on first load, a transition holds what its refetch reaches, and a server render sends it to the client, which adopts it without fetching.

import { query, useQuery, useSWR, useInfiniteQuery, useFetch } from 'what-framework/data';

query(key, fetcher) is the signal-native read. useQuery, useSWR, useInfiniteQuery and useFetch keep the shapes of TanStack Query and SWR, over the same entries: a query() and a useSWR on one key are one request and one value. The full model, with the tests behind each guarantee, is in DATA.md.

query

query(key, fetcher, options?) returns an async value for the entry its key names. Read it in JSX like any value: before the first value lands it suspends its <Suspense>; after that, a refetch keeps the old value on screen and pending() says a new one is on its way. Every reader of a key shares one request.

import { Suspense, refresh } from 'what-framework';
import { query } from 'what-framework/data';

const fetchUser = (key, { signal }) => fetch(`/api/users/${key[1]}`, { signal }).then((r) => r.json());

export function Profile(props) {
  // A function key follows its signals: a new id fetches (or shows, if cached) its entry
  const user = query(() => ['user', props.id], fetchUser, { staleTime: 30_000 });
  return (
    <Suspense fallback={<p>Loading…</p>}>
      <h1 class={user.pending() ? 'stale' : ''}>{user().name}</h1>
      <button onClick={() => refresh(user)}>Reload</button>
    </Suspense>
  );
}
  • Key: a string, an array, or a function of signals returning one; null, false or undefined is no key. An array key is joined into one normalized string (['user', 7] is 'user:7', with : inside a segment escaped), so a string key and the equivalent array key are one entry everywhere.
  • Fetcher: fetcher(key, { signal }) gets the key as written and the request's AbortSignal. A key nothing reads any more is aborted.
  • Options: staleTime (how long a landed value is fresh; default 0), gcTime (how long an entry nothing reads is kept; default 5 minutes), retry, retryDelay, initialData.
  • Transitions: a key change inside startTransition commits with the new key's value, in one flush. An invalidateQueries() inside an action's transition refetches into the same commit that drops its optimistic overlay.
  • Errors reach the nearest <ErrorBoundary>; reset() fetches again.

useSWR

SWR's shape. It never suspends: data() is the cached value, or fallbackData, or null.

import { useSWR } from 'what-framework/data';

export function Notifications() {
  const { data, isLoading, isValidating, mutate } = useSWR(
    '/api/notifications',
    (url, { signal }) => fetch(url, { signal }).then((r) => r.json()),
    { refreshInterval: 30_000 },
  );
  return (
    <section>
      {isLoading() ? <p>Loading…</p> : <p>{(data() || []).length} new{isValidating() ? ' (refreshing)' : ''}</p>}
      <button onClick={() => mutate([])}>Mark all read</button>
    </section>
  );
}
  • isLoading(): no data yet, and fetching. isValidating(): fetching.
  • mutate(data, shouldRevalidate = true) puts data in the cache for every reader of the key, then fetches again; mutate() alone revalidates.
  • Options: dedupingInterval (default 2000: a fetch within it answers a new reader, a focus or a reconnect), revalidateOnFocus, revalidateOnReconnect, refreshInterval, fallbackData, keepPreviousData, onSuccess, onError.

Conditional and dependent fetching

A null or false key pauses the hook, and so does a key function that throws (its input is not there yet), as in SWR. A function key is read reactively, so a dependent query is written the way it reads:

import { useSWR } from 'what-framework/data';

const json = (url, { signal }) => fetch(url, { signal }).then((r) => r.json());

export function Projects() {
  const user = useSWR('/api/me', json);
  // Waits for the user, then fetches under the user's own key
  const projects = useSWR(() => `/api/projects?uid=${user.data().id}`, json);
  return <p>{(projects.data() || []).length} projects</p>;
}

useQuery

TanStack Query's shape, over the same cache.

import { signal } from 'what-framework';
import { useQuery } from 'what-framework/data';

export function Repos() {
  const org = signal('whatfw');
  const repos = useQuery({
    queryKey: () => ['repos', org()],
    queryFn: ({ queryKey, signal }) => fetch(`/api/orgs/${queryKey[1]}/repos`, { signal }).then((r) => r.json()),
    staleTime: 60_000,
    keepPreviousData: true,
  });
  return (
    <div>
      <input value={org()} onInput={(e) => org(e.target.value)} />
      {repos.isLoading() ? <p>Loading…</p> : <p>{(repos.data() || []).length} repositories</p>}
    </div>
  );
}
  • queryKey: a key, or a function of signals; the query follows it to the new key's entry, and with keepPreviousData (or placeholderData: (previous) => previous) shows the previous key's data meanwhile (isPlaceholderData()). A static array is read once, when the hook is created.
  • queryFn({ queryKey, signal }). queryKey is this query's own key, as an array, even when another spelling of it ('todos:1' for ['todos', 1]) created the cache entry they share. A signal it reads synchronously refetches the entry under the same key; prefer putting such inputs in a function key, so each value has its own entry.
  • enabled: a boolean, a signal or a thunk, gating automatic fetching (mount, focus, polling, invalidation). An explicit refetch() runs regardless and is never answered from the staleTime window. A disabled query with nothing cached reports status() === 'idle'.
  • Status: status() is 'idle', 'loading', 'success' or 'error'; fetchStatus() is 'fetching' or 'idle'; plus isLoading(), isFetching(), isError(), isSuccess(), isIdle(), dataUpdatedAt().
  • Options: staleTime (0), gcTime/cacheTime (5 minutes), refetchOnWindowFocus, refetchOnReconnect, refetchInterval, retry (total attempts, 3), retryDelay, select, placeholderData, initialData, and onSuccess/onError/onSettled, which fire once per landing for the query that started the fetch.

useInfiniteQuery

The pages are one cache entry, data() is { pages, pageParams } (pageParams[i] names pages[i]), and invalidating its key refetches page one and replaces the list.

import { useInfiniteQuery } from 'what-framework/data';

export function Feed() {
  const feed = useInfiniteQuery({
    queryKey: ['feed'],
    queryFn: ({ pageParam, signal }) => fetch(`/api/feed?cursor=${pageParam}`, { signal }).then((r) => r.json()),
    initialPageParam: 0,
    getNextPageParam: (lastPage) => lastPage.nextCursor,
  });
  return (
    <div>
      <ul>{feed.data().pages.flatMap((page) => page.items).map((item) => <li key={item.id}>{item.title}</li>)}</ul>
      <button disabled={!feed.hasNextPage() || feed.isFetchingNextPage()} onClick={() => feed.fetchNextPage()}>More</button>
    </div>
  );
}

On an empty list fetchNextPage() and fetchPreviousPage() fetch the first page from initialPageParam, so either can start a list created with enabled: false or retry a first page that failed. A newer page fetch supersedes one in flight, and the flag of the direction it replaced comes down. refetchOnWindowFocus defaults to false here: a focus refetch replaces the list with page one.

useFetch

One URL's JSON, from the cache: data() (null, or initialData, until the first response), error(), isLoading(), refetch() (never rejects) and mutate(value). url may be a function of signals. Options: method, body, headers, transform, initialData, fetch.

Cache Management

import { invalidateQueries, prefetchQuery, setQueryData, getQueryData, clearCache } from 'what-framework/data';

export async function afterSave(todo) {
  setQueryData(['todo', todo.id], todo);       // every reader of the key shows it now
  await invalidateQueries(['todos']);         // a prefix: also ['todos', 1]; resolves when refetched
}

export function warm() {
  return prefetchQuery(['todos'], (key, { signal }) => fetch('/api/todos', { signal }).then((r) => r.json()));
}

export function logout() {
  clearCache();  // nothing requested before this lands after it
  return getQueryData(['todos']);  // undefined
}
  • invalidateQueries(keyOrPredicate, { exact, hard }) marks the entries stale and refetches the ones something shows (a query whose enabled is false stays asleep). An array key is a prefix on segment boundaries unless exact; a predicate receives each normalized key; hard empties first. Inside a transition the refetch joins it, and the returned promise resolves once the refetches have landed.
  • invalidatePath(path) refetches what was read on path: a route's preload data, and every query read while the page was at that path. A server action's revalidate calls it.
  • setQueryData lands a value now, dropping a fetch in flight for the key. getQueryData is undefined when nothing is cached, null after a hard invalidation.
  • clearCache() (logout) drops what is in flight; entries a reader shows stay attached to it, empty (a hook settles on 'idle', a mounted query() fetches again).

On the server

A server render keeps a cache of its own per request, so one request's data never answers another. query() fetches there: a read before the value lands suspends its <Suspense>, renderDocument and the streaming renderers wait for it, and the value goes to the client in the hydration payload under its key, where it is adopted with no request. The hooks do not fetch on the server: there, and while the page hydrates, they render their first state (loading, or their own initialData), and right after hydration what the cache holds, with no request for a value the page carried. For the request's own data, a page loader works too.

Live Demo: Data Fetching