React
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.
Exercise 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.
Show example solution
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;
Test yourself
-
If the product is in the cart, what does ADD do?
- Add new item
- Delete
- Increment quantity
- Nothing
Show answer
Increment quantity — If exists, increment quantity.
-
REMOVE method
To remove a product in REMOVE, use ____.
Show answer
To remove a product in REMOVE, use filter.
-
Match the cartReducer actions
- ADD
- add/inc
- REMOVE
- filter
- CLEAR
- empty
- total
- reduce
Next lesson: Cart context