Suspense
A product viewer where the component that reads the data has no loading or error branches. <Suspense> shows the
loading state, an error boundary shows failures, and product 999 is there to fail on purpose.
intermediateuseFetchsuspenseerrors
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { createClient } from "@hyper-fetch/core";
export const client = createClient({ url: "https://dummyjson.com" });
export type Product = {
id: number;
title: string;
description: string;
price: number;
rating: number;
thumbnail: string;
};
/** dummyjson answers an unknown id with `404 { message }`. */
export const getProduct = client.createRequest<{
response: Product;
error: { message: string };
// `delay` slows dummyjson down so the Suspense fallback is easy to see.
queryParams: { select: string; delay: number };
}>()({
endpoint: "/products/:productId",
});
Run locally
npx tiged BetterTyped/hyper-fetch/examples/react/suspense hyper-fetch-react-suspense && cd hyper-fetch-react-suspense && npm install && npm run devWhat it shows
suspense: truemakesuseFetchsuspend until the first response arrives.throwOnError: truethrows the request error to the closest error boundary once the request settles.- An error boundary in app code, with a "Try again" button that remounts the component and fetches again.
- Cached data does not suspend. A product you opened before renders at once.
How it works
api.tsdefinesgetProductwith anerrortype for dummyjson's404 { message }body. Thedelayquery param makes the fallback visible.ProductDetailscallsuseFetch(..., { suspense: true, throwOnError: true }). While the request is in flight the hook throws a promise and React shows the nearest<Suspense>fallback.- When the response is an error, the hook throws the error object itself, not an
Errorinstance. The boundary inerror-boundary.tsxstores it asunknown, andgetMessagereadsmessagesafely. - "Try again" calls
reset()on the boundary, which renders the children again. Errors are not stored in the cache, so the component suspends and fetches the product again. Apppasseskey={productId}to the boundary, so switching products starts with a clean boundary instead of the previous error.- Successful responses are cached. Going back to a product renders it right away and refreshes it in the background.
const { data } = useFetch(getProduct.setParams({ productId }), { suspense: true, throwOnError: true });
The data type stays nullable, because the return type does not depend on the options. A single if (!data) check
satisfies TypeScript.
When to use it
- Apps that already use
<Suspense>for code splitting or streaming and want data loading in the same boundaries. - Screens with several requests that should show one loading state together.
Related
Summary
You let <Suspense> handle loading and an error boundary handle failures with suspense and throwOnError, so the
component that shows the product only deals with data.
