Part 10 / Topic 2 of 8
Action objects and a pure reducer
An action is a plain object that names what happened - never what the new state should be. { type: "add", dish } says "a dish was added"; it is cartReducer's job, and only its job, to decide what the cart looks like afterward. examples/02_cart_reducer_pure.jsx defines the whole cart's update logic as one function:
// examples/02_cart_reducer_pure.jsx
export function cartReducer(state, action) {
switch (action.type) {
case "add": {
const existing = state.items.find((item) => item.id === action.dish.id);
if (existing) {
return {
items: state.items.map((item) =>
item.id === action.dish.id ? { ...item, quantity: item.quantity + 1 } : item,
),
};
}
return { items: [...state.items, { ...action.dish, quantity: 1 }] };
}
case "remove":
return { items: state.items.filter((item) => item.id !== action.id) };
case "clear":
return { items: [] };
default:
throw new Error(`Unknown action type: ${action.type}`);
}
}
Every single type string the cart supports is listed in one switch, in one function, instead of scattered across however many event handlers call setState. The default case throwing (rather than silently returning state unchanged) turns a typo'd action type into a loud, immediate error instead of a UI that quietly does nothing.
Done here? The practice set for Part 10 — including the solutions — is on the part page.