Recipes/SWR
SWR
The entry point @qubeejs/react/swr fetches a list’s request through SWR. It needs swr 2.
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);How it works
Section titled “How it works”useQubeeSWR(request, options?)isuseSWRwith the key['qubee', request.uri, request.headers]and a fetcher that callsfetchQubeePage. It returns whatuseSWRreturns, withdatatyped asPaginatedResult<Article>.- The key is built from the committed state: it changes once per navigation, after any debounce.
keepPreviousDatais on by default, so the last page stays on screen while the next one loads. PasskeepPreviousData: falseto 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,fallbackDataand the rest — exceptfetcher, which is aQubeeFetcher: a function with the shape offetch, not an SWR fetcher. Without one, the hook uses the nearest<QubeeFetchProvider>’s, else the globalfetch. - A
nullrequest fetches nothing and shows no page — only thefallbackDatayou gave it, if any — as withuseQubeeQuery:keepPreviousDatakeeps a page while the next request loads, never across anullone. The request after anullone 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
okis aQubeeFetchErrorinerror. list.isPendingcovers the debounce and the navigation,isValidatingthe request.