Skip to main content

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.

intermediatevalidationuseFetcherrorstypescript
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>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/response-mapping hyper-fetch-react-response-mapping && cd hyper-fetch-react-response-mapping && npm install && npm run dev
What it shows
  1. setResponseMapper runs on every response, before send() resolves and before a hook gets the data.
  2. zod transform renames and computes fields, so components read name, salePrice and inStock.
  3. Typed output flows from the mapper into useFetch: data has the app shape without any extra generics.
  4. Invalid data becomes an error: the mapper returns a failed response with the ZodError, and the UI lists the issues.

How it works​

  1. api.ts describes the API with apiProductSchema and wraps it in productsSchema, whose transform builds the app shape. z.input types the raw response for createRequest, z.output types what the app gets.

  2. getProducts.setResponseMapper() receives the full response. Failed responses pass through untouched. Successful ones are parsed with safeParse:

    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 };
  3. The request type is rebuilt from the mapper's return type, so useFetch(getProducts) returns data of type Products and the components never see title or discountPercentage.

  4. The switch drops fields with ?select=title,thumbnail, like a backend release that renamed them. The mapper turns that response into an error, and ValidationError checks error instanceof z.ZodError to show the issues instead of a broken grid.

  5. 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.

When to use it
  • 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.

Summary

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.