When the visitor reloads the page, the browser runs app.js again from the top. Every variable starts over, so const cart = [] makes a new, empty cart, and the Mug the visitor added is gone.
localStorage is a small store the browser keeps for each site, and it survives reloads. localStorage.setItem(key, text) saves a text under a key; localStorage.getItem(key) gives it back, or null when nothing was saved. It keeps only strings, so an array goes in as JSON: JSON.stringify turns it into a string, and JSON.parse turns the string back into an array.
const favorites = [2, 5];
localStorage.setItem("favorites", JSON.stringify(favorites));
// after a reload:
const text = localStorage.getItem("favorites"); // "[2,5]"
const ids = JSON.parse(text); // [2, 5]
The check adds a Mug and a Lamp, looks into the browser's localStorage, reloads the page and adds one more Mug. Your page must show:
> click "Add to cart" in "Mug", then in "Lamp" → text: Total: $41
> the browser's localStorage
cart = [{"id":1,"name":"Mug",…,"quantity":1},{"id":3,"name":"Lamp",…}]
> reload the page
item: Mug x 1 $12
item: Lamp x 1 $29
text: Total: $41
> click "Add to cart" in "Mug"
item: Mug x 2 $24
text: Total: $53
Your task: save the cart at the end of render, which runs after every change. At the start, read the saved cart and, when there is one, push its lines into cart.
Assignment
Follow the Coding Tutorial to save the cart in localStorage on every change and read it back when the page loads.
Hint
Save with JSON.stringify(cart) and read back with JSON.parse(saved). Check that saved is not null first: on a first visit nothing is stored.
Free plan: 30 tutor messages. PRO is unlimited.
