Response mapping
A product grid that never renders data it does not understand. Every response goes through a zod schema that checks it and turns the API fields into the fields the components use.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useFetch } from "@hyper-fetch/react";
import { useState } from "react";
import { z } from "zod";
import { FIELDS, getProducts, type Product } from "./api";
const ProductCard = ({ product }: { product: Product }) => (
<article className="product">
<img src={product.image} alt="" width={96} height={96} />
<div>
<strong>{product.name}</strong>
<p>
<del className="muted">${product.price.toFixed(2)}</del> <ins>${product.salePrice.toFixed(2)}</ins>
</p>
<small>{product.inStock ? "In stock" : <mark>Sold out</mark>}</small>
</div>
</article>
);
const ValidationError = ({ error }: { error: Error }) => {
// The mapper returns the ZodError as the response error, so it can be told apart from network errors.
if (!(error instanceof z.ZodError)) return <p className="error">Could not load products: {error.message}</p>;
const issues = [...new Set(error.issues.map((issue) => `${issue.path.at(-1)?.toString()}: ${issue.message}`))];
return (
<article>
<header>
<strong className="error">The API returned data the app does not understand</strong>
</header>
<p>The response mapper rejected it, so no component received broken data. Issues:</p>
<ul>
{issues.map((issue) => (
<li key={issue}>
<code>{issue}</code>
</li>
))}
</ul>
</article>
);
};
export const App = () => {
const [broken, setBroken] = useState(false);
// `data` already has the app shape: `name`, `salePrice` and `inStock` come from the mapper, not from the API.
const { data, error, loading } = useFetch(
getProducts.setQueryParams({ limit: 6, select: broken ? "title,thumbnail" : FIELDS }),
);
return (
<main className="container">
<hgroup>
<h1>Products</h1>
<p>The API response is validated with zod and mapped to the app shape before any component sees it.</p>
</hgroup>
<label>
<input type="checkbox" role="switch" checked={broken} onChange={(event) => setBroken(event.target.checked)} />
Simulate a breaking API change (the response loses <code>price</code>, <code>stock</code> and{" "}
<code>discountPercentage</code>)
</label>
{loading && !data && !error && <p aria-busy="true">Loading products...</p>}
{error && <ValidationError error={error} />}
{data && !error && (
<section>
<p className="muted">
Showing {data.items.length} of {data.total} products
</p>
<div className="products">
{data.items.map((product) => (
<ProductCard key={product.id} product={product} />
))}
</div>
</section>
)}
</main>
);
};
npx tiged BetterTyped/hyper-fetch/examples/react/response-mapping hyper-fetch-react-response-mapping && cd hyper-fetch-react-response-mapping && npm install && npm run devsetResponseMapperruns on every response, beforesend()resolves and before a hook gets the data.- zod
transformrenames and computes fields, so components readname,salePriceandinStock. - Typed output flows from the mapper into
useFetch:datahas the app shape without any extra generics. - Invalid data becomes an error: the mapper returns a failed response with the
ZodError, and the UI lists the issues.
How it works
-
api.tsdescribes the API withapiProductSchemaand wraps it inproductsSchema, whosetransformbuilds the app shape.z.inputtypes the raw response forcreateRequest,z.outputtypes what the app gets. -
getProducts.setResponseMapper()receives the full response. Failed responses pass through untouched. Successful ones are parsed withsafeParse:const result = productsSchema.safeParse(response.data);if (!result.success) return { ...response, data: null, error: result.error, success: false as const };return { ...response, data: result.data }; -
The request type is rebuilt from the mapper's return type, so
useFetch(getProducts)returnsdataof typeProductsand the components never seetitleordiscountPercentage. -
The switch drops fields with
?select=title,thumbnail, like a backend release that renamed them. The mapper turns that response into an error, andValidationErrorcheckserror instanceof z.ZodErrorto show the issues instead of a broken grid. -
The cache keeps the raw response and the mapper runs when it is read, so every consumer of the request gets the same mapped result.
The opposite direction works the same way: setPayloadMapper() maps the payload before it is sent, and
setRequestMapper() can validate or change the whole request.
- APIs you do not control, where a field can change without notice.
- Backends that use different names or units than your UI.
- Values computed from the response that several components need.
Related
One setResponseMapper call validates the response with zod, maps it to the app shape and types it for every hook. Data
that fails the schema reaches the UI as an error, never as broken props.
