Skip to main content

Shop

A shop on the dummyjson products and carts API, with four routes: the catalog, a product page, the cart and the checkout. Add a few products and reload the page: the cart is still there, read from localStorage without a request.

advanceduseInfiniteFetchoptimisticpersistenceformsrouter
import { useSubmit } from "@hyper-fetch/react";
import type { FormEvent } from "react";
import { Link } from "react-router";

import { getCart, toPayload } from "../../api/cart";
import { placeOrder, ValidationError } from "../../api/checkout";
import { client } from "../../api/client";
import { Price } from "../../components/Price";
import { useCart } from "../cart/use-cart";

export const CheckoutPage = () => {
const { cart } = useCart();
const { submit, submitting, data: order, error, onSubmitSuccess } = useSubmit(placeOrder);
// A `ValidationError` comes from the request mapper, anything else from the server or the network.
const fieldErrors = error instanceof ValidationError ? error.fields : {};

onSubmitSuccess(() => {
// The order is placed: empty the cart in the cache, which also saves the empty cart to localStorage.
client.cache.update(getCart, (cached) =>
cached?.data ? { data: { ...cached.data, products: [], totalQuantity: 0, total: 0, discountedTotal: 0 } } : {},
);
});

const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!cart) return;
const form = new FormData(event.currentTarget);
submit({
payload: {
userId: 1,
products: toPayload(cart).products,
shipping: {
name: String(form.get("name") ?? ""),
email: String(form.get("email") ?? ""),
address: String(form.get("address") ?? ""),
},
},
});
};

if (order) {
return (
<article>
<h1>Thank you!</h1>
<p>
Order #{order.id} with {order.totalQuantity} item(s) is placed. You paid{" "}
<Price value={order.discountedTotal} />.
</p>
<Link to="/">Continue shopping</Link>
</article>
);
}

return (
<article>
<h1>Checkout</h1>
<p className="muted">
{cart?.totalQuantity ?? 0} item(s), <Price value={cart?.discountedTotal ?? 0} /> with discounts.
</p>
{/* `noValidate`: the request validates the fields, so the browser does not stop the submit first. */}
<form onSubmit={handleSubmit} noValidate>
<label>
Full name
<input name="name" autoComplete="name" aria-invalid={fieldErrors.name ? true : undefined} />
{fieldErrors.name && <small>{fieldErrors.name}</small>}
</label>
<label>
Email
<input name="email" type="email" autoComplete="email" aria-invalid={fieldErrors.email ? true : undefined} />
{fieldErrors.email && <small>{fieldErrors.email}</small>}
</label>
<label>
Shipping address
<textarea
name="address"
rows={2}
autoComplete="street-address"
aria-invalid={fieldErrors.address ? true : undefined}
/>
{fieldErrors.address && <small>{fieldErrors.address}</small>}
</label>
{error && !(error instanceof ValidationError) && <p className="error">{error.message}</p>}
<button type="submit" aria-busy={submitting} disabled={submitting}>
Place order
</button>
</form>
</article>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/apps/shop hyper-fetch-apps-shop && cd hyper-fetch-apps-shop && npm install && npm run dev
What it shows
  1. Infinite catalog: useInfiniteFetch pages through products, a search or a category, with the filters in the URL (Infinite scroll, Filters in the URL).
  2. Debounced search: bounce starts a new list when typing stops (Search as you type).
  3. Prefetch on hover: the product page usually opens without a loading state (Prefetching).
  4. Cart in the cache: every screen reads the cart with useFetch, and a localStorage cache storage keeps it after a reload (Cache persistence).
  5. Optimistic add to cart: the badge changes at once, the server's prices replace the local ones when it answers (Optimistic updates).
  6. Validated checkout: a request mapper checks the form, useSubmit returns the field errors (Payload validation, Forms).

How it works​

  1. api/client.ts creates the client with a synchronous localStorage cache storage. Every cached response is saved there, so the cart and the pages you visited are back on the first render after a reload.

  2. api/products.ts has three list endpoints: all products, a search and a category. catalogRequest() picks one from the filters, and catalogPagination describes how all three page with skip and limit. CatalogPage passes both to useInfiniteFetch, and an IntersectionObserver calls fetchNextPage() near the end of the list.

  3. api/cart.ts defines getCart and saveCart. dummyjson prices the products it receives, so every save sends the whole cart with merge: false, and the answer has the totals for exactly that cart. queued: true sends the saves one by one.

  4. useCart() is the one hook every screen uses. Its change() passes the optimistic update per call, because adding a new line needs the product's title and price, which the payload does not carry:

    optimistic(getCart)
    .set((data) => changeQuantity(data, product, delta))
    .commit(({ data, response }) => ({ ...data, discountedTotal: response.data.discountedTotal }))
    .rollback(({ data }) => changeQuantity(data, product, -delta));

    The lines change at once. The totals come from the server on commit, and a failed save undoes only its own change.

  5. dummyjson does not store carts. getCart has a one-week staleTime and the hook reads it with revalidate: false, so the saved cart is never replaced by the server's original. The update returns revalidate: false for the same reason. With a real API, use a short staleTime and let it refetch.

  6. api/checkout.ts validates the shipping fields in setRequestMapper. A throw ends the request with that error and nothing reaches the network. CheckoutPage checks error instanceof ValidationError to show the field messages. Server errors, such as 400 for an empty cart, show as one message.

  7. After a successful order, client.cache.update(getCart, ...) empties the cart. The header badge, the cart page and localStorage all update from that one write.

  8. Layout shows a global loading indicator with useIsFetching(client) and the cart badge from useCart().

When to use it
  • Stores, booking flows and any app with a cart, a basket or a draft that must survive a reload.
  • Catalogs with filters, where users expect the URL to keep the search and the category.
  • Forms whose rules belong to the request, so every caller gets the same validation.

Summary

The cart is one cache entry: persisted by the cache storage, changed optimistically by useCart() and emptied with cache.update(). The catalog is one useInfiniteFetch over three endpoints, and the checkout gets its field errors from a request mapper.