Show contents
Chapter 5 of 6 · 30 min
Project: a cooperative's task board
By the end of this chapter, you'll be able to
- Design the state, actions and reducer of a complete application
- Compute the displayed information from the state, without storing it
- Produce safe rendering that escapes all external data
- Test the core of the application without a browser, then wire it to the DOM
Step 1: the architecture
The application is split into layers, from the purest to the most concrete:
| Layer | Role | Testable without a browser? |
|---|---|---|
| Reducer | (state, action) → new state | yes |
| Derived functions | visible cards, columns, progress | yes |
| Rendering | state → HTML (or DOM), escaping everything | yes, in text form |
| Wiring | events → actions, saving, debounce | no: it's the thinnest possible layer |
An important rule: the state stores only what can't be computed. The progress percentage or the list of visible cards are derived from the cards and the filter: storing them would create a risk of contradiction.
Rendering escapes every title: a card named <img …> is displayed as text.
Text description of the animation
- The click handler just dispatches an action.
- The reducer checks that the column exists, then copies the card with its new column.
- The state holds only the base data.
- Progress is recomputed from the cards: it can never be wrong.
- Rendering escapes every title: a card named <img …> is displayed as text.
Step 2: the core of the application and its tests
// --- The core of the application: a state, actions, a pure reducer ---
const COLUMNS = ["to do", "in progress", "done"];
function reducer(state, action) {
switch (action.type) {
case "add": {
const title = action.title.trim().slice(0, 80);
if (!title) return state;
const card = { id: state.nextId, title, column: "to do", owner: action.owner ?? null };
return { ...state, cards: [...state.cards, card], nextId: state.nextId + 1 };
}
case "move": {
if (!COLUMNS.includes(action.to)) return state;
return { ...state, cards: state.cards.map((c) => (c.id === action.id ? { ...c, column: action.to } : c)) };
}
case "remove":
return { ...state, cards: state.cards.filter((c) => c.id !== action.id) };
case "filter":
return { ...state, filter: action.text.trim().toLowerCase() };
default:
return state;
}
}
// --- Derived functions: computed from the state, never stored ---
const visible = (state) => state.cards.filter((c) => c.title.toLowerCase().includes(state.filter));
const byColumn = (state) => Object.fromEntries(COLUMNS.map((col) => [col, visible(state).filter((c) => c.column === col)]));
const progress = (state) => {
const total = state.cards.length;
return total === 0 ? 0 : Math.round((100 * state.cards.filter((c) => c.column === "done").length) / total);
};
// --- Rendering: a function of the state, which escapes all external text ---
const escapeHtml = (t) => String(t).replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
function render(state) {
const columns = Object.entries(byColumn(state)).map(([col, cards]) =>
`<section><h2>${col} (${cards.length})</h2>${cards.map((c) => `<p data-id="${c.id}">${escapeHtml(c.title)}</p>`).join("")}</section>`);
return `<p>Progress: ${progress(state)} %</p>${columns.join("")}`;
}
// --- Tests of the reducer and the rendering ---
const check = (condition, message) => { if (!condition) throw new Error(`test failed: ${message}`); };
const empty = { cards: [], nextId: 1, filter: "" };
const frozen = Object.freeze({ ...empty, cards: Object.freeze([]) });
const one = reducer(frozen, { type: "add", title: " Fix the pump " });
check(one.cards[0].title === "Fix the pump" && one !== frozen, "add without changing the frozen state");
check(reducer(one, { type: "add", title: " " }) === one, "empty title ignored");
check(reducer(one, { type: "move", id: 1, to: "bin" }) === one, "unknown column refused");
check(!render(reducer(empty, { type: "add", title: "<script>x</script>" })).includes("<script>"), "title escaped");
console.log("Tests: OK");
// --- A usage session ---
let state = empty;
const actions = [
{ type: "add", title: "Fix the well pump" },
{ type: "add", title: "Order the millet seeds" },
{ type: "add", title: "Train Ama on spreadsheets" },
{ type: "add", title: "<img src=x onerror=alert(1)>" },
{ type: "move", id: 1, to: "done" },
{ type: "move", id: 2, to: "in progress" },
{ type: "remove", id: 4 },
];
for (const action of actions) state = reducer(state, action);
console.log(render(state).replaceAll("<section>", "\n<section>"));
state = reducer(state, { type: "filter", text: "SEEDS" });
console.log("Filter \"seeds\":", visible(state).map((c) => c.title).join(", "));
Tests: OK
<p>Progress: 33 %</p>
<section><h2>to do (1)</h2><p data-id="3">Train Ama on spreadsheets</p></section>
<section><h2>in progress (1)</h2><p data-id="2">Order the millet seeds</p></section>
<section><h2>done (1)</h2><p data-id="1">Fix the well pump</p></section>
Filter "seeds": Order the millet seeds
Choices worth noticing:
- The reducer validates actions: empty title ignored, title cut to 80 characters, unknown column refused. An invalid action returns the state unchanged, so no useless render.
- The frozen-state test (
Object.freeze) proves the reducer never changes the state it receives: any change would throw an error in strict mode. - The rendering test checks that a title's
<script>tag never appears as is in the produced HTML. - The booby-trapped card
<img src=x onerror=…>is first added, then removed by a moderator: at no point could it run. - The filter is case-insensitive (
toLowerCase): "SEEDS" finds "seeds".
Step 3: wiring it to the page
In the browser, only a thin layer remains: create the store, subscribe the render, turn events into actions. The search goes through a debounce, and the state is saved in the browser's local storage on every change. Try it:
The cooperative's task boardHTML · 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
The whole page is built with textContent: try adding a task named <b>urgent</b>, it's displayed as is. The "Delete" buttons have an accessible label that says which task they delete, for screen readers. In the lab, the page is isolated for security and local storage may be unavailable: saving then fails silently, without stopping the application from working.
Your turn
Worked exercise
Solved exercise: a save that survives corrupted data
Write save(state, storage) and load(storage). The save records only the cards and the next identifier (not the filter, which is temporary), with a version number. Loading must return the empty state if nothing is saved, if the JSON is unreadable or if the data doesn't match the expected format. Test with a fake storage that mimics localStorage.
Hint 1
JSON.parse throws an error on broken text: wrap it in a try/catch. JSON.parse(null) returns null, which must also be handled.Hint 2
nextId is an integer, and each card with every(…): integer id, text title, known column.Show the solution and common mistakes
// A fake localStorage for the example: same methods, stored in a Map.
const storage = { data: new Map(), getItem(k) { return this.data.get(k) ?? null; }, setItem(k, v) { this.data.set(k, String(v)); } };
const KEY = "board:v1";
const EMPTY_STATE = { cards: [], nextId: 1, filter: "" };
function save(state, storage) {
const { cards, nextId } = state;
storage.setItem(KEY, JSON.stringify({ version: 1, cards, nextId }));
}
function load(storage) {
try {
const raw = JSON.parse(storage.getItem(KEY));
const valid = raw?.version === 1 && Number.isInteger(raw.nextId) && Array.isArray(raw.cards)
&& raw.cards.every((c) => Number.isInteger(c.id) && typeof c.title === "string" && ["to do", "in progress", "done"].includes(c.column));
return valid ? { ...EMPTY_STATE, cards: raw.cards, nextId: raw.nextId } : EMPTY_STATE;
} catch {
return EMPTY_STATE;
}
}
console.log(load(storage) === EMPTY_STATE, "← nothing saved: empty state");
save({ cards: [{ id: 1, title: "Fix the pump", column: "in progress" }], nextId: 2, filter: "pump" }, storage);
const reread = load(storage);
console.log(reread.cards[0].title, "|", reread.nextId, "| filter:", JSON.stringify(reread.filter));
storage.setItem(KEY, "{ broken JSON");
console.log(load(storage) === EMPTY_STATE, "← unreadable data: empty state");
storage.setItem(KEY, JSON.stringify({ version: 1, nextId: 2, cards: [{ id: 1, title: "x", column: "bin" }] }));
console.log(load(storage) === EMPTY_STATE, "← unknown column: empty state");
true ← nothing saved: empty state
Fix the pump | 2 | filter: ""
true ← unreadable data: empty state
true ← unknown column: empty state
Local storage data comes from outside the program: another tab, an old version of the application or a browser extension may have written anything there. It's validated like user input. The version number will let you, the day the format changes, convert old saves instead of losing them.
Common mistakes:
- Trusting the reread content: a card without a title would crash the render on
c.title.toLowerCase(), and the application would never start again for that user. - Saving the search filter: when the user comes back to the page, cards would seem to have disappeared for no visible reason.
Summary
- 1A robust application is split into layers: pure reducer, derived functions, rendering, then minimal wiring.
- 2Store only what can't be computed; the rest is derived from the state.
- 3Rendering escapes all external data, or uses textContent.
- 4The core of the application is tested without a browser, frozen state included.
- 5Data reread from local storage is validated like user input.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.