SWR
SWR calls a fetcher for every key and caches what it returns. A typed HyperFetch request makes a good fetcher: SWR owns
the cache, revalidation and retries, and HyperFetch sends the request with exec(), with your client's auth,
interceptors, mappers and adapter. There is no package to install beyond @hyper-fetch/core and SWR.
- Typed fetchers: Params, response and error types come from the request.
- Errors SWR understands:
throwOnErrorrejects with theerrorof a failed response, so it lands inerror. - Stable keys:
request.cacheKeyis built from the method, endpoint, params and query params. - One cache:
exec()skips the HyperFetch dispatcher and cache, so nothing is cached or retried twice.
Fetching
SWR tells a failure by a rejected promise, so set throwOnError:
import useSWR from "swr";
const getUsers = client.createRequest<{ response: User[] }>()({
endpoint: "/users",
throwOnError: true,
});
export const useUsers = () =>
useSWR(getUsers.cacheKey, async () => {
const { data } = await getUsers.exec();
return data;
});
For a request with params, set them before reading the key, so each set of params gets its own entry:
export const useUser = (userId: number) => {
const request = getUser.setParams({ userId });
return useSWR(request.cacheKey, async () => (await request.exec()).data);
};
SWR does not pass an AbortSignal to the fetcher, so these calls are not cancelled when the component unmounts.
Mutations
useSWRMutation passes the argument of trigger() as arg. Send it as the payload and revalidate the list afterwards:
import useSWRMutation from "swr/mutation";
const createUser = client.createRequest<{ response: User; payload: NewUser }>()(
{
endpoint: "/users",
method: "POST",
throwOnError: true,
},
);
export const useCreateUser = () =>
useSWRMutation(getUsers.cacheKey, async (_key, { arg }: { arg: NewUser }) => {
const { data } = await createUser.exec({ payload: arg });
return data;
});
Mutating under the key of getUsers makes SWR revalidate the list once the mutation resolves.
- You already use SWR and want typed requests without rewriting the data layer.
- You move to HyperFetch screen by screen, with both libraries running side by side.
- You want HyperFetch adapters (GraphQL, Firebase, Axios) or a generated SDK behind an SWR cache.
SWR and the HyperFetch cache don't share data. Read a given endpoint through one of them, or different screens show different data.
- Fetchers call
exec(), so SWR owns caching, revalidation and retries. throwOnErrorturns failed responses into rejections, set per call, per request or for a whole SDK.request.cacheKeyis a stable key, anduseSWRMutationsends mutations withexec({ payload }).