React · Lesson 91 of 120
Project: Product Data
A fake API.
Every shop starts with data. We don't have a real server, so a small file stands in for one. It returns products after a short delay, and can fail, just like a real network.
- Data first
- A pretend server
- Delays and failures
api.js
Products is our pretend database, five items, each with an id, name, price, type, and stock. Wait creates a delay, like a real network. Get products returns them all. Get product finds one, or throws an error if it's missing. Place order pretends to save an order, and returns its number. Run it. Five products, and a clear message for a missing one.
api.jsjavascript
const PRODUCTS = [
{ id: 1, name: "Trail 500", price: 849.5, type: "bike", stock: 12 },
{ id: 2, name: "City 200", price: 450, type: "bike", stock: 0 },
{ id: 3, name: "Volt 7", price: 2199, type: "bike", stock: 4 },
{ id: 4, name: "Helmet", price: 40, type: "gear", stock: 30 },
{ id: 5, name: "Lights", price: 25, type: "gear", stock: 18 },
];
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
export const getProducts = () => wait(300).then(() => PRODUCTS);
export async function getProduct(id) {
await wait(300);
const product = PRODUCTS.find(p => p.id === Number(id));
if (!product) throw new Error(`Product ${id} not found`);
return product;
}
export async function placeOrder(order) {
await wait(500);
return { id: 1043, ...order };
}Output
products: 5 missing product: Product 9 not found
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses shop.css
.box{padding:7px 12px;margin:5px 0} a{color:#0b6bcb} small{display:inline;margin-left:8px}
button:disabled{background:#ddd;color:#777}
header.box{display:flex;gap:14px;align-items:center;background:#eaf8fd}Also uses cartReducer.js
export function cartReducer(items, action) {
switch (action.type) {
case "add": {
const found = items.find(i => i.id === action.product.id);
if (found) return items.map(i => (i.id === found.id ? { ...i, qty: i.qty + 1 } : i));
return [...items, { ...action.product, qty: 1 }];
}
case "setQty":
return items.map(i => (i.id === action.id ? { ...i, qty: action.qty } : i)).filter(i => i.qty > 0);
case "clear":
return [];
default:
throw new Error("Unknown action: " + action.type);
}
}Also uses Filters.jsx
export default function Filters({ query, setQuery, type, setType }) {
return (
<div>
<input id="q" value={query} onChange={e => setQuery(e.target.value)} placeholder="Search" />{" "}
<select id="type" value={type} onChange={e => setType(e.target.value)} style={{ fontSize: 19 }}>
<option value="all">All</option><option value="bike">Bikes</option><option value="gear">Gear</option>
</select>
</div>
);
}Also uses Field.jsx
export default function Field({ name, label, form, setForm, errors }) {
return (
<label style={{ display: "block", margin: "6px 0" }}>
{label} <input id={name} name={name} value={form[name]}
onChange={e => setForm({ ...form, [name]: e.target.value })} />
{errors[name] && <small>{errors[name]}</small>}
</label>
);
}Also uses validate.js
export function validate(form) {
const errors = {};
if (!form.name.trim()) errors.name = "Please enter your name";
if (!form.email.includes("@")) errors.email = "Please enter a valid email";
if (form.address.trim().length < 5) errors.address = "Please enter your full address";
return errors;
}Also uses useCheckout.js
import { useState } from "react";
import { useCart } from "./CartContext";
import { placeOrder } from "./api";
import { validate } from "./validate";
export function useCheckout(form) {
const { items, total, dispatch } = useCart();
const [errors, setErrors] = useState({});
const [order, setOrder] = useState(null);
const [sending, setSending] = useState(false);
async function submit(e) {
e.preventDefault();
const found = validate(form);
if (Object.keys(found).length > 0) return setErrors(found);
setSending(true);
setOrder(await placeOrder({ ...form, items, total }));
dispatch({ type: "clear" });
}
return { errors, order, sending, submit, total };
}Also uses ProductPage.jsx
import { useState, useEffect } from "react";
import { useParams, Link } from "react-router";
import { getProduct } from "./api";
import { useCart } from "./CartContext";
export default function ProductPage() {
const { id } = useParams();
const { dispatch } = useCart();
const [product, setProduct] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
let ignore = false;
getProduct(id).then(p => !ignore && setProduct(p)).catch(e => !ignore && setError(e.message));
return () => { ignore = true; };
}, [id]);
if (error) return <p className="box">{error}. <Link to="/">Back to the shop</Link></p>;
if (!product) return <p>Loading...</p>;
return (<div className="box"><h2>{product.name}</h2><p>£{product.price} · {product.stock} in stock</p>
<button id="addp" onClick={() => dispatch({ type: "add", product })}>Add to cart</button></div>);
}Also uses NotFound.jsx
import { Link, useLocation } from "react-router";
export default function NotFound() {
const { pathname } = useLocation();
return (
<div className="box">
<h2>Page not found</h2>
<p>Nothing lives at {pathname}.</p>
<Link to="/">Back to the shop</Link>
</div>
);
}Also uses pages.js
export { default as Layout } from "./Layout";
export { default as ProductList } from "./ProductList";
export { default as ProductPage } from "./ProductPage";
export { default as CartPanel } from "./CartPanel";
export { default as Checkout } from "./Checkout";
export { default as NotFound } from "./NotFound";Also uses ProductCard.jsx
export default function ProductCard({ product }) {
return (
<div className="box">
<b>{product.name}</b> — £{product.price}
{product.stock === 0 && <small>Sold out</small>}
</div>
);
}Also uses ProductList.jsx
import { useState, useEffect } from "react";
import { getProducts } from "./api";
import ProductCard from "./ProductCard";
export default function ProductList() {
const [products, setProducts] = useState([]);
useEffect(() => {
getProducts().then(setProducts);
}, []);
return <div>{products.map(p => <ProductCard key={p.id} product={p} />)}</div>;
}Also uses CartContext.jsx
import { createContext, useContext, useReducer } from "react";
import { cartReducer } from "./cartReducer";
const CartContext = createContext(null);
export function CartProvider({ children }) {
const [items, dispatch] = useReducer(cartReducer, []);
const count = items.reduce((n, i) => n + i.qty, 0);
return <CartContext value={{ items, dispatch, count }}>{children}</CartContext>;
}
export const useCart = () => useContext(CartContext);Also uses CartPanel.jsx
import { useCart } from "./CartContext";
export default function CartPanel() {
const { items } = useCart();
if (items.length === 0) return <p className="box">Your cart is empty.</p>;
return (
<div className="box">
<h2>Your cart</h2>
{items.map(i => <p key={i.id}>{i.qty} × {i.name}</p>)}
</div>
);
}Also uses Checkout.jsx
import { useState } from "react";
import Field from "./Field";
export default function Checkout() {
const [form, setForm] = useState({ name: "", email: "", address: "" });
function submit(e) {
e.preventDefault();
console.log("order details:", JSON.stringify(form));
}
const props = { form, setForm, errors: {} };
return (
<form onSubmit={submit} className="box">
<Field name="name" label="Name" {...props} />
<Field name="email" label="Email" {...props} />
<Field name="address" label="Address" {...props} />
<button id="place">Place order</button>
</form>
);
}Also uses Layout.jsx
import { Link, Outlet } from "react-router";
import { useCart } from "./CartContext";
export default function Layout() {
const { count } = useCart();
return (<>
<header className="box">
<Link to="/"><b>Northwind Bikes</b></Link>
<Link id="cartlink" to="/cart">Cart ({count})</Link>
</header>
<main><Outlet /></main>
</>);
}Also uses App.jsx
import { getProducts, getProduct } from "./api";
getProducts().then(ps => console.log("products:", ps.length));
getProduct(9).catch(e => console.log("missing product:", e.message));
export default function App() { return <p className="box">Testing the API...</p>; }Also uses actions.json
[{"wait": 600}]Summary
Our pretend server can list products, find one, and place orders. Next, the layout.
Key takeaways- getProducts
- getProduct
- placeOrder
Next up: Project: Layout — header and main