AI Hints
Home›React Tutorial›Project: Quantities and Totals
React · Lesson 101 of 120

Project: Totals

Derived values.

⏱ 2 min read▶ Video at 1:25:01🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

The cart needs a total. It's not new state. It's derived from the items, every render.

  • A total
  • Not new state
  • Derived

CartContext.jsx

Total is derived from the items, the price times the quantity, added up. The context now shares it with everyone. The cart panel shows each line's price, and the total. Nothing is stored twice, so it can never be wrong. We add two helmets and the Volt 7. Run it.

CartContext.jsxjsx
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);
  const total = items.reduce((sum, i) => sum + i.price * i.qty, 0);
  return <CartContext value={{ items, dispatch, count, total }}>{children}</CartContext>;
}
export const useCart = () => useContext(CartContext);
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 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
import { useCart } from "./CartContext";
export default function ProductCard({ product }) {
  const { dispatch } = useCart();
  const soldOut = product.stock === 0;
  return (
    <div className="box">
      <b>{product.name}</b> — £{product.price}{" "}
      <button id={"add" + product.id} disabled={soldOut} onClick={() => dispatch({ type: "add", product })}>
        {soldOut ? "Sold out" : "Add to cart"}
      </button>
    </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 CartPanel.jsx
import { useCart } from "./CartContext";
export default function CartPanel() {
  const { items, dispatch, total } = useCart();
  if (items.length === 0) return <p className="box">Your cart is empty.</p>;
  const setQty = (id, qty) => dispatch({ type: "setQty", id, qty });
  return (
    <div className="box">
      <h2>Your cart</h2>
      {items.map(i => <div key={i.id}>
        <button id={"less" + i.id} onClick={() => setQty(i.id, i.qty - 1)}>−</button> {i.qty}
        <button id={"more" + i.id} onClick={() => setQty(i.id, i.qty + 1)}>+</button> {i.name} — £{(i.price * i.qty).toFixed(2)}
      </div>)}
      <p><b>Total: £{total.toFixed(2)}</b></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 "./shop.css";
import { CartProvider, useCart } from "./CartContext";
import ProductList from "./ProductList";
import CartPanel from "./CartPanel";
import Checkout from "./Checkout";
function Header() {
  const { count } = useCart();
  return <header className="box"><b>Northwind Bikes</b> Cart ({count})</header>;
}
export default function App() {
  return <CartProvider><Header /><main><CartPanel /><ProductList /></main></CartProvider>;
}
Also uses actions.json
[{"wait": 600}, {"click": "#add4", "times": 2}, {"click": "#add3"}]

Summary

Totals are derived in the provider, and shared through context. Next, saving the cart.

Key takeaways
  • reduce
  • Derived
  • Always right
Next up: Project: Saving the Cart — localStorage