An AI assistant opened a pull request: a discount code box under the Corner Shop's cart. The visitor types a code, clicks the button, and the total drops. The codes live in CODES = { SPRING5: 5, WELCOME10: 10 }, in dollars off. Here is the part of the AI's Cart to review:
const [total, setTotal] = useState(subtotal);
function applyCode() {
setTotal(subtotal - CODES[code]);
}
…
<button onClick={applyCode}>
<svg … aria-hidden="true">…</svg>
</button>
<p>Total: ${total}</p>
A quick look says it works: SPRING5 takes $49 to $44. A review finds three problems. The button holds only a hidden icon, so it has no name: a screen reader says just "button", and the check finds no button named "Apply". A code that isn't in CODES gives undefined, so the total becomes $NaN and the visitor gets no message. And the total was copied into state once, so after the visitor removes a line, it stays the same.
A smaller example of a lookup that misses: with const SIZES = { S: 1, M: 2 }, SIZES["XL"] is undefined, and 10 - undefined is NaN. Check for undefined before you use the value.
The check types a wrong code, then a good one, then removes the Plant. Your cart must show:
button: Apply text: Total: $49 > type "FREEBIES", click "Apply" → + alert: Unknown code: FREEBIES > type "SPRING5", click "Apply" → - alert: Unknown code: FREEBIES, text: Total: $44 > click "Remove Plant" → - item: Plant $15, text: Total: $29
Your task: in src/Cart.jsx, keep the discount in state and work out the total at every draw, write the word Apply in the code button, and show a message for an unknown code that a good code clears.
Assignment
Follow the Coding Tutorial to fix the three problems in the AI's discount code box: a total that follows the lines, a button with a name, and a message for an unknown code.
Hint
Keep what the code takes off in state, not the total. A code that is not in CODES gives undefined: check for it first, and stop there.
Free plan: 30 tutor messages. PRO is unlimited.
