Skip to content
Recipes/SWR

SWR

The entry point @qubeejs/react/swr fetches a list’s request through SWR. It needs swr 2.

src/articles/use-articles-swr.ts
import type { QubeeListHandle } from '@qubeejs/react';
import { useQubeeSWR } from '@qubeejs/react/swr';
import type { Article, articleList } from './article-list';
/** The page the list's committed state asks for, cached by SWR. */
export function useArticlesSWR(list: QubeeListHandle<typeof articleList>) {
return useQubeeSWR<Article>(list.request, { revalidateOnFocus: false });
}

In a component:

const list = useQubeeList(articleList);
const { data, error, isValidating } = useArticlesSWR(list);
  • useQubeeSWR(request, options?) is useSWR with the key ['qubee', request.uri, request.headers] and a fetcher that calls fetchQubeePage. It returns what useSWR returns, with data typed as PaginatedResult<Article>.
  • The key is built from the committed state: it changes once per navigation, after any debounce.
  • keepPreviousData is on by default, so the last page stays on screen while the next one loads. Pass keepPreviousData: false to the hook to turn it off: the hook’s default wins over one set in an <SWRConfig> above.
  • The options are SWR’s own — revalidateOnFocus, refreshInterval, fallbackData and the rest — except fetcher, which is a QubeeFetcher: a function with the shape of fetch, not an SWR fetcher. Without one, the hook uses the nearest <QubeeFetchProvider>’s, else the global fetch.
  • A null request fetches nothing and shows no page — only the fallbackData you gave it, if any — as with useQubeeQuery: keepPreviousData keeps a page while the next request loads, never across a null one. The request after a null one shows no page from before it until its own arrives.
  • The fetcher is not part of the key: two hooks with the same request share one cache entry, whatever their fetchers.
  • A status that is not ok is a QubeeFetchError in error.
  • list.isPending covers the debounce and the navigation, isValidating the request.