Command Palette

Search for a command to run...

Hectal
Phase 15: State Management at Scale
React · Exercise 4 of 5 PreviousNext
Advanced

A cart that survives reloads

Build useCart with Zustand and the persist middleware, saved under the localStorage key cart. The state has items (an array of product names), drawerOpen (a boolean, starts false) and actions add(name), clear() and toggleDrawer().

Only items may be saved: use partialize so drawerOpen and the actions stay out of storage. Give the store version: 1.

Each product button has className="add" (already in the starter). <span id="count"> shows the number of items, #clear empties the cart, and #toggle opens and closes a drawer <aside id="drawer"> that lists the items (render the aside only when open).

What Check tests

  1. Adding two products shows 2
  2. The drawer opens and lists the items
  3. localStorage cart holds the items with version 1
  4. drawerOpen is not saved
  5. Clear empties the cart and the saved copy
  6. The drawer closes again

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

Runs in your browser. Your code is saved here.

Your page

Press Run to see the page.

Console

Nothing logged yet.