Until now, each click changed the page directly. The cart now shows up in two places, the header's Cart (2) and the list under Your cart. Changing both by hand is how a page ends up disagreeing with itself. The fix: keep the cart's state in one place, an array, and draw the page from it.
The pattern has two parts: code that changes the state and then calls render(), and render() itself, which redraws everything from the state. Here it is with a like counter:
let likes = 0;
const likesText = document.querySelector("#likes");
function render() {
likesText.textContent = likes + " likes";
}
function like() {
likes += 1;
render();
}
render();
For a list, render rebuilds it whole: element.replaceChildren(...items) removes the old children and puts in the new ones, so nothing is shown twice or left behind. One render() at the end of the file draws the page before any click.
The check opens the page, then clicks "Add to cart" in Mug, Lamp and Mug again. It must print:
> open the page text: Cart (0) list (empty) > click "Add to cart" in "Mug" + text: Cart (1) + item: Mug $12 > click "Add to cart" in "Lamp" + text: Cart (2) + item: Lamp $29 > click "Add to cart" in "Mug" + text: Cart (3) + item: Mug $12
Your task: in app.js, make an empty array cart, a function render that fills #cart-list from it with cartLine and writes Cart (n), and a function addToCart(id) that finds the product, pushes it into cart and calls render. The list's click listener calls addToCart, and the file ends with one call to render.
Assignment
Follow the Coding Tutorial to keep the cart in an array and draw the header count and the cart list from it with render.
Hint
Never patch the page in the click listener: change cart, then call render(). replaceChildren wants each li as its own argument, so spread the array with ....
Free plan: 30 tutor messages. PRO is unlimited.
