React · Lesson 96 of 120
Project: Cart State
A reducer.
The cart has the most logic in the app. Adding, changing quantities, and clearing. A reducer keeps all of it in one pure function, that's easy to test.
- Most logic
- One pure function
- Easy to test
cartReducer.js
The cart is a list of items, each a product plus a quantity. Adding a product that's already there increases its quantity. Otherwise it's added with a quantity of one. Set quantity changes one line, and removes it when the quantity reaches zero. Clear empties the cart. We test it on its own, with no components at all. Run it.
cartReducer.jsjavascript
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);
}
}Output
after two adds: [{"id":4,"name":"Helmet","price":40,"qty":2}]
after setting qty to 0: []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 api.js
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 };
}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 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";
import Filters from "./Filters";
export default function ProductList() {
const [products, setProducts] = useState(null);
const [error, setError] = useState(null);
const [query, setQuery] = useState("");
const [type, setType] = useState("all");
useEffect(() => { getProducts().then(setProducts).catch(e => setError(e.message)); }, []);
if (error) return <small>Could not load products: {error}</small>;
if (!products) return <p>Loading products...</p>;
const shown = products.filter(p => (type === "all" || p.type === type)
&& p.name.toLowerCase().includes(query.toLowerCase()));
return (<>
<Filters query={query} setQuery={setQuery} type={type} setType={setType} />
{shown.map(p => <ProductCard key={p.id} product={p} />)}
</>);
}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 { cartReducer } from "./cartReducer";
const helmet = { id: 4, name: "Helmet", price: 40 };
let cart = [];
cart = cartReducer(cart, { type: "add", product: helmet });
cart = cartReducer(cart, { type: "add", product: helmet });
console.log("after two adds:", JSON.stringify(cart));
cart = cartReducer(cart, { type: "setQty", id: 4, qty: 0 });
console.log("after setting qty to 0:", JSON.stringify(cart));
export default function App() { return <p className="box">Reducer tested.</p>; }Summary
The cart reducer handles add, set quantity, and clear, and works without any components. Next, sharing the cart.
Key takeaways- add
- setQty
- clear
Next up: Project: Cart Context — share the cart