Command Palette

Search for a command to run...

Hectal
Phase 9: Context and Reducers
React · Exercise 3 of 5 PreviousNext
Intermediate

A shopping cart with a reducer

The cart below is fully wired: every button already dispatches an action. Only cartReducer is missing. Write it.

Actions: added (with item: add a new row with qty: 1, or increase qty if the item is already in the cart), increased and decreased (with id: change that row's qty by one; a row that reaches 0 is removed), and cleared (empty the cart).

Return new arrays and objects; never change cart itself. The rows (li.item), #count (N items, counting quantities) and #total (Total: ₹N) are already calculated from the state.

What Check tests

  1. The cart starts empty
  2. Adding Chai adds one row with quantity 1
  3. Adding Chai again increases its quantity instead of adding a row
  4. Adding Samosa and pressing + gives 4 items, ₹70
  5. Pressing − until Chai reaches 0 removes its row
  6. Clear empties the cart
  7. Unknown actions throw

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.