Show contents
Chapter 5 of 6 · 30 min
Final project: an interactive shopping list
By the end of this chapter, you'll be able to
- Separate the application's state (the data) from its display
- Write a render function that rebuilds the display from the state
- Wire a form and buttons to functions that change the state
- Make the application accessible to the keyboard and to screen readers
Step 1: thinking in state and display
A classic beginner's mistake: changing the page all over the place, click after click. Adding an <li> here, changing a text there… Very soon, the display no longer matches the data, and nobody knows which one to believe.
The method of modern applications (and of libraries such as React or Vue) is simpler:
- the state is the single source of truth: an array of items;
- each user action changes the state, and only the state;
- after each change, a
render()function rebuilds the display from the state.
Another action follows exactly the same path: toggle(), then render().
Text description of the animation
- The user adds 2 kilos of rice.
- The listener doesn't touch the page: it asks for a new version of the state.
- The state now contains the item.
- render() clears the displayed list and rebuilds it entirely from the state.
- The page and the summary always match the data, whatever the action.
- Another action follows exactly the same path: toggle(), then render().
Step 2: the logic, without the page
The functions that handle the state never touch the DOM. So you can write and test them on their own, right here:
let nextId = 1;
function add(items, name, quantity) {
const clean = name.trim();
if (clean === "") throw new Error("The item's name is empty.");
if (!Number.isInteger(quantity) || quantity < 1) throw new Error("The quantity must be a positive whole number.");
const existing = items.find((i) => i.name.toLowerCase() === clean.toLowerCase());
if (existing) {
return items.map((i) => (i === existing ? { ...i, quantity: i.quantity + quantity } : i));
}
return [...items, { id: nextId++, name: clean, quantity, bought: false }];
}
function toggle(items, id) {
return items.map((i) => (i.id === id ? { ...i, bought: !i.bought } : i));
}
function remove(items, id) {
return items.filter((i) => i.id !== id);
}
function summary(items) {
const left = items.filter((i) => !i.bought).length;
return `${left} item(s) to buy out of ${items.length}`;
}
let list = [];
list = add(list, "Rice", 2);
list = add(list, " Tomatoes ", 6);
list = add(list, "rice", 1);
list = toggle(list, 2);
console.log(list.map((i) => `${i.bought ? "[x]" : "[ ]"} ${i.name} x${i.quantity}`).join(" | "));
console.log(summary(list));
try {
list = add(list, "Milk", 0);
} catch (error) {
console.log("Refused:", error.message);
}
list = remove(list, 1);
console.log(summary(list));
[ ] Rice x3 | [x] Tomatoes x6
1 item(s) to buy out of 2
Refused: The quantity must be a positive whole number.
0 item(s) to buy out of 1
The choices worth noticing:
- each function returns a new array (
map,filter,[...items, …]) instead of changing the old one. That way you always know when the state changes: only on the assignmentlist = …; - adding an item that's already there ("rice" and "Rice") increases its quantity instead of creating a duplicate;
- invalid data throws an error (
throw new Error(...)), which the interface will catch to display a message.
Step 3: display and events
let items = [];
let filter = "all"; // "all", "to-buy" or "bought"
const form = document.querySelector("#add");
const error = document.querySelector("#error");
const ul = document.querySelector("#items");
const status = document.querySelector("#status");
function render() {
ul.replaceChildren(); // empties the list
const visible = items.filter((i) =>
filter === "all" ? true : filter === "bought" ? i.bought : !i.bought);
for (const i of visible) {
const li = document.createElement("li");
li.dataset.id = i.id;
li.classList.toggle("bought", i.bought);
const name = document.createElement("span");
name.textContent = `${i.name} × ${i.quantity}`;
const tick = document.createElement("button");
tick.type = "button";
tick.className = "toggle";
tick.textContent = i.bought ? "Put back" : "Bought";
tick.setAttribute("aria-pressed", String(i.bought));
const del = document.createElement("button");
del.type = "button";
del.className = "delete";
del.textContent = "Delete";
del.setAttribute("aria-label", `Delete ${i.name}`);
li.append(name, tick, del);
ul.append(li);
}
status.textContent = summary(items);
}
form.addEventListener("submit", (event) => {
event.preventDefault();
try {
items = add(items, form.elements.name.value, Number(form.elements.quantity.value));
error.textContent = "";
form.reset();
form.elements.name.focus();
} catch (e) {
error.textContent = e.message;
}
render();
});
ul.addEventListener("click", (event) => {
const button = event.target.closest("button");
if (!button) return;
const id = Number(button.closest("li").dataset.id);
if (button.classList.contains("toggle")) items = toggle(items, id);
if (button.classList.contains("delete")) items = remove(items, id);
render();
});
document.querySelector("#filter").addEventListener("change", (event) => {
filter = event.target.value;
render();
});
render();
replaceChildren()with no argument empties an element.render()starts from scratch every time: it's simple, and more than fast enough for a few hundred items.li.dataset.idwrites adata-idattribute: it links each displayed row to its item in the state.- A single listener on the list handles all the buttons, including those created later (the delegation from the previous chapter).
- For accessibility:
aria-pressedannounces the state of the "Bought" button,aria-labelsays which item you're deleting, and the summary is in a<p role="status">, announced on every change.
Your turn
Here's the complete application, ready to work. Try it, then add the improvements requested in the comments.
Project: the shopping listHTML · CSS · JS
Preview
Console
(Nothing in the console yet.)Your code runs in an isolated page, with no access to this site or the Internet · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
In a published application, you'd keep the list between two visits with localStorage, the browser's storage: localStorage.setItem("list", JSON.stringify(items)) on every render(), and JSON.parse(localStorage.getItem("list") ?? "[]") at start-up. The lab, isolated for your safety, has no access to it.
Worked exercise
Worked exercise: sorting the list
Write a function sortItems(items) that returns a new array with the items to buy first, then the items already bought. Within each group, items are in alphabetical order, ignoring case and handling accents properly. The original array must not be changed.
Hint 1
sort changes the array it's called on: sort a copy, [...items].Hint 2
Number(true) is 1 and Number(false) is 0. a.name.localeCompare(b.name, "en") compares two texts according to the language's rules. The || operator moves on to the second criterion when the first one gives 0.Show the solution and common mistakes
function sortItems(items) {
return [...items].sort((a, b) => Number(a.bought) - Number(b.bought) || a.name.localeCompare(b.name, "en"));
}
const items = [
{ id: 1, name: "Éclairs", quantity: 12, bought: false },
{ id: 2, name: "apples", quantity: 1, bought: true },
{ id: 3, name: "Coffee", quantity: 1, bought: false },
{ id: 4, name: "bananas", quantity: 6, bought: false },
];
console.log(sortItems(items).map((i) => i.name).join(", "));
console.log(items[0].name);
bananas, Coffee, Éclairs, apples
Éclairs
In render(), you then just write for (const i of sortItems(visible)).
Common mistakes:
- Writing
items.sort(...): the state array is changed in place, outside the functions designed for that. - Comparing with
a.name < b.name: capital letters come before lowercase ones, and accented letters after all the others, so "Éclairs" would end up last in its group.
Summary
- 1The state (the data) is the single source of truth; the page is only its reflection.
- 2State functions return a new array and never touch the DOM.
- 3render() rebuilds the display from the state, after every change.
- 4One listener per container is enough thanks to delegation, even for elements created later.
- 5aria-pressed, aria-label and role="status" make the application understandable without seeing it.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.