React: A shopping cart reducer

Carts are a classic reducer: several actions, each with clear rules, and totals computed from the result.

What to build

A product list and a cart managed by a reducer.

Requirements

  • Products: Tea (3.50), Biscuits (2.25), Honey (6.00). Each has a button Add NAME that dispatches added.
  • The cart is a ul with the id cart with one li per product in it, in the order first added, with the attribute data-id set to the product's id, showing NAME × QTY in a span and the buttons +, - and Remove. - at 1 removes the line.
  • A p with the id total shows Total: T with two decimals, and a p with the id shipping shows Free shipping when the total is at least 10, and otherwise Add X more for free shipping (X with two decimals).

Constraints

All cart changes go through one reducer; nothing derived is stored.

Example

Adding Tea twice and Honey once shows "Tea × 2", "Honey × 1", "Total: 13.00" and "Free shipping".

Why it works

The reducer holds the rules for adding, changing and removing lines in one pure function, and the total and the shipping note are computed from the cart, so they can never disagree with it.

Hints

Hint 1

State: an array of { id, name, price, qty }. "added" increases qty if the product is already in the cart.

Hint 2

"changed" with a new qty of 0 removes the line; the total and the shipping note are derived.

Solution

Show one correct solution (try it yourself first)
import { useReducer } from "react";

const PRODUCTS = [
  { id: "tea", name: "Tea", price: 3.5 },
  { id: "biscuits", name: "Biscuits", price: 2.25 },
  { id: "honey", name: "Honey", price: 6 },
];
const FREE_SHIPPING = 10;

function cartReducer(cart, action) {
  switch (action.type) {
    case "added": {
      const line = cart.find((l) => l.id === action.product.id);
      if (line) return cart.map((l) => (l.id === line.id ? { ...l, qty: l.qty + 1 } : l));
      return [...cart, { ...action.product, qty: 1 }];
    }
    case "changed":
      if (action.qty <= 0) return cart.filter((l) => l.id !== action.id);
      return cart.map((l) => (l.id === action.id ? { ...l, qty: action.qty } : l));
    case "removed":
      return cart.filter((l) => l.id !== action.id);
    default:
      throw new Error("Unknown action: " + action.type);
  }
}

export default function App() {
  const [cart, dispatch] = useReducer(cartReducer, []);
  const total = cart.reduce((sum, l) => sum + l.price * l.qty, 0);

  return (
    <div>
      {PRODUCTS.map((p) => (
        <button key={p.id} onClick={() => dispatch({ type: "added", product: p })}>
          Add {p.name}
        </button>
      ))}
      <ul id="cart">
        {cart.map((l) => (
          <li key={l.id} data-id={l.id}>
            <span>
              {l.name} × {l.qty}
            </span>
            <button onClick={() => dispatch({ type: "changed", id: l.id, qty: l.qty + 1 })}>+</button>
            <button onClick={() => dispatch({ type: "changed", id: l.id, qty: l.qty - 1 })}>-</button>
            <button onClick={() => dispatch({ type: "removed", id: l.id })}>Remove</button>
          </li>
        ))}
      </ul>
      <p id="total">Total: {total.toFixed(2)}</p>
      <p id="shipping">{total >= FREE_SHIPPING ? "Free shipping" : "Add " + (FREE_SHIPPING - total).toFixed(2) + " more for free shipping"}</p>
    </div>
  );
}

Lesson: Reducers: organising state changes →