Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 41 ยท Projects and Practice

Project: A Shopping Cart with Redux

Build a shopping cart in Redux: a product catalog slice, cart quantities, money in cents, coupon codes, memoized totals and a checkout thunk that updates several slices at once.

A shopping cart is a richer project than a todo list because the state has relationships: the cart refers to products, totals depend on both, a coupon changes prices, and a checkout touches several slices at the same time. Those are exactly the situations where Redux's design (one place for state, one pipeline for changes, selectors for derived values) pays off.

All logic runs in the editors on a stand-in store. At the end we show the Redux Toolkit structure for a real app.

The requirements

  • A catalog of products with price and stock.
  • Add to cart, change the quantity, remove a line. The cart cannot exceed stock.
  • Apply one coupon code (percentage or fixed amount).
  • Show subtotal, discount, tax and total.
  • Checkout: reduce stock, clear the cart, record an order.

Design decisions

  1. Money in integer cents. 19.99 as a float causes errors like 0.1 + 0.2. Store 1999 and format only for display.
  2. The cart stores ids and quantities, not copies of products. The price shown always comes from the catalog; if it changes, the cart changes with it.
  3. Derived values are selectors: line totals, subtotal, discount, tax, total.
  4. Checkout is one action (checkout/completed) that the catalog, cart and orders slices all handle. One dispatch, one state transition, one entry in DevTools.
flowchart TD
  subgraph state
    CAT["catalog: products, stock"]
    CART["cart: lines {productId: qty}, coupon"]
    ORD["orders: list"]
  end
  CAT --> SEL["selectors: subtotal, discount, tax, total"]
  CART --> SEL
  CHK["checkout/completed"] --> CAT
  CHK --> CART
  CHK --> ORD

One action can be handled by several slices.

Step 1: slices

JS Catalog, cart and orders slices

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice where the stock cap is enforced: the action carries max so the reducer stays a pure function of (state, action). In a real app you would read it in a thunk (getState().catalog[id].stock) and dispatch.

Step 2: selectors for money

Selectors compute everything shown in the summary. Coupons come in two types, and we round to whole cents at one well-defined point.

JS Totals, coupons and tax

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The numbers are checked by hand: 2 notebooks (900) + 1 pen set (1299) is 2199; 10% is 220; tax on 1979 is 158; the total is 2137 cents.

Step 3: checkout

Checkout must verify stock again (another tab or user may have bought items), build an order, and dispatch one action. Because it needs getState, it is a thunk. We also simulate payment, which can fail.

JS A checkout thunk

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A failed payment leaves the cart untouched, and success changes three slices through a single action. The "start" and "failure" actions only update a status flag; everything that must change together goes through checkout/completed.

The Redux Toolkit structure (read-only)

JavaScript
// Real Redux Toolkit sketch (read-only)
const cartSlice = createSlice({
  name: 'cart',
  initialState: { lines: {}, coupon: null },
  reducers: {
    added(state, action) {
      const { id, max } = action.payload;
      state.lines[id] = Math.min((state.lines[id] ?? 0) + 1, max);
    },
    couponApplied(state, action) { state.coupon = action.payload; },
  },
  extraReducers: (builder) => {
    builder.addCase(checkout.fulfilled, (state) => { state.lines = {}; state.coupon = null; });
  },
});

checkout is a createAsyncThunk; catalogSlice and ordersSlice also use extraReducers for checkout.fulfilled. If product data comes from a server, make the catalog an RTK Query endpoint, keep the cart as a slice, and write selectors that combine both.

Things to watch out for

  • Never trust the client for prices. The server must recompute totals at checkout; client-side Redux is only for display.
  • Rounding: decide once when to round (here at each percentage step) and test with awkward amounts.
  • Stale carts: persisted carts (persistence) may reference products that no longer exist. Selectors should skip them.
  • Concurrency: disable the checkout button while status === 'processing' to avoid double submission.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why store prices in integer cents?

    0.1 + 0.2 is not exactly 0.3; whole cents are exact.
  2. 2. Why does the cart store product ids and quantities instead of product copies?

    A single source of truth avoids stale duplicates.
  3. 3. How does checkout update three slices consistently?

    One action means one state transition, and DevTools shows it as one step.
  4. 4. Why must the server recompute the total?

    Never trust the client for money.

Summary

  • Money as integer cents; derived totals as selectors.
  • The cart holds ids and quantities; the catalog is the single source of product data.
  • One checkout/completed action updates catalog, cart and orders together.
  • A thunk handles validation and the async payment; failures leave state intact.
  • Real apps recompute prices on the server and guard against stale and double submissions.

Next: Project: an async data dashboard