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.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
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>
);
};
npx tiged BetterTyped/hyper-fetch/examples/apps/shop hyper-fetch-apps-shop && cd hyper-fetch-apps-shop && npm install && npm run dev- Infinite catalog:
useInfiniteFetchpages through products, a search or a category, with the filters in the URL (Infinite scroll, Filters in the URL). - Debounced search:
bouncestarts a new list when typing stops (Search as you type). - Prefetch on hover: the product page usually opens without a loading state (Prefetching).
- Cart in the cache: every screen reads the cart with
useFetch, and alocalStoragecache storage keeps it after a reload (Cache persistence). - Optimistic add to cart: the badge changes at once, the server's prices replace the local ones when it answers (Optimistic updates).
- Validated checkout: a request mapper checks the form,
useSubmitreturns the field errors (Payload validation, Forms).
How it works
-
api/client.tscreates the client with a synchronouslocalStoragecache storage. Every cached response is saved there, so the cart and the pages you visited are back on the first render after a reload. -
api/products.tshas three list endpoints: all products, a search and a category.catalogRequest()picks one from the filters, andcatalogPaginationdescribes how all three page withskipandlimit.CatalogPagepasses both touseInfiniteFetch, and anIntersectionObservercallsfetchNextPage()near the end of the list. -
api/cart.tsdefinesgetCartandsaveCart. dummyjson prices the products it receives, so every save sends the whole cart withmerge: false, and the answer has the totals for exactly that cart.queued: truesends the saves one by one. -
useCart()is the one hook every screen uses. Itschange()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.
-
dummyjson does not store carts.
getCarthas a one-weekstaleTimeand the hook reads it withrevalidate: false, so the saved cart is never replaced by the server's original. The update returnsrevalidate: falsefor the same reason. With a real API, use a shortstaleTimeand let it refetch. -
api/checkout.tsvalidates the shipping fields insetRequestMapper. A throw ends the request with that error and nothing reaches the network.CheckoutPagecheckserror instanceof ValidationErrorto show the field messages. Server errors, such as400for an empty cart, show as one message. -
After a successful order,
client.cache.update(getCart, ...)empties the cart. The header badge, the cart page andlocalStorageall update from that one write. -
Layoutshows a global loading indicator withuseIsFetching(client)and the cart badge fromuseCart().
- 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.
Related
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.
