CodeBlanks Logo Icon CodeBlanks

Cart reducer

Write the cart reducer with add, remove and clear actions.

Cart reducer

This lesson writes the cartReducer function. Three action types: ADD (add product), REMOVE (remove product), CLEAR (empty cart).

In the ADD case, if the product is already in the cart, increment its quantity; otherwise add it as a new item. Check with items.find(i => i.id === payload.id).

In the REMOVE case, drop the item with items.filter(i => i.id !== payload.id). In the CLEAR case, return to initial state: { '{ items: [], total: 0 }' }.

Total computation

Total must be updated on every ADD/REMOVE. The cleanest method: after computing new items in the reducer, recompute total: const items = ...; const total = items.reduce((sum, i) => sum + i.price * i.qty, 0); return { '{ items, total }' };.

This is the single source principle: if items is right, total is right. Deriving total from items (instead of a separate state) keeps consistency.

This pattern can also be done later with useMemo. But computing inside the reducer keeps state managed in one place; debugging is easier.

Practice Write cartReducer

Complete the skeleton. Write a cartReducer function. Take (state, action). With switch(action.type), in the ADD case return { '{ ...state, items: [...state.items, action.payload], total: state.total + action.payload.price }' }. In REMOVE, const items = state.items.filter(i => i.id !== action.payload.id); const total = items.reduce((s, i) => s + i.price * i.qty, 0); return { '{ ...state, items, total }' }. In CLEAR, return { '{ items: [], total: 0 }' }. default returns state. Export it.

Starter code

App.jsx
// Write the cartReducer function here

Sample solution

App.jsx
function cartReducer(state, action) {
  switch (action.type) {
    case "ADD":
      return { ...state, items: [...state.items, action.payload], total: state.total + action.payload.price };
    case "REMOVE": {
      const items = state.items.filter((i) => i.id !== action.payload.id);
      const total = items.reduce((s, i) => s + i.price * i.qty, 0);
      return { ...state, items, total };
    }
    case "CLEAR":
      return { items: [], total: 0 };
    default:
      return state;
  }
}

export default cartReducer;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 If the product is in the cart, what does ADD do?

  • Add new item
  • Delete
  • Increment quantity Correct answer
  • Nothing

Explanation: If exists, increment quantity.

2 REMOVE method

Question
To remove a product in REMOVE, use ____.
Answer
To remove a product in REMOVE, use filter.

Explanation: Remove with filter.

3 Match the cartReducer actions

Term Meaning
ADD add/inc
REMOVE filter
CLEAR empty
total reduce

All lessons in Intermediate