Step 9 / 9100%

Step 9

Step 9 — Saving and Finishing Touches

25 min

Persist tasks with localStorage and clear completed tasks.

Definition

Persistence is an application's ability to keep its data after the page is closed. For this, the browser offers localStorage, a small storage space tied to the site, which keeps key / value pairs from one visit to the next.

Since localStorage can only store text, we use serialization: converting an array or an object into JSON text in order to save it, then doing the reverse to read it back.

Goal of this step

Final stretch! For now, reloading the page makes all your tasks disappear. You will save them in the browser with localStorage, then add a button to clear the completed tasks.

This step changes almost nothing about the application's appearance, but it makes it truly usable: a tool that forgets everything on every visit isn't much use. You will also bring all your code together and check the complete file.

Here is the plan for this step:

  • write load() and save() to read from and write to localStorage;
  • call save() after every change to the data;
  • add the clearCompleted function and connect it to its button;
  • reread the project's complete code to check that everything is in place.

Understanding localStorage

localStorage is a small storage space built into the browser. It keeps data even after the page or the browser is closed. However, it can only store text: to save an array of objects, we convert it to JSON.

principle
const data = [{ id: 1, text: "Test", done: false }];

// Save: array → JSON text
localStorage.setItem("my-key", JSON.stringify(data));

// Load: JSON text → array
const reloaded = JSON.parse(localStorage.getItem("my-key"));

You have already come across JSON.stringify and JSON.parse in the lesson on objects.

The methods to know

  • setItem(key, value) stores a value under a name, replacing the old one if there was one.
  • getItem(key) reads the value back, or returns null if the key doesn't exist.
  • removeItem(key) deletes a specific key, and clear() empties the whole storage of the site.

The data stays tied to the site that wrote it: another web page cannot read your application's data. However, it remains stored on your computer and is not protected: so we never put passwords or sensitive information in it.

Its space is limited to a few megabytes, which is more than enough for a to-do list. For very large amounts of data, or to share information between several devices, other solutions are used, such as a database on a server.

Writing load and save

In todo.js, replace the line let tasks = []; with the block below. Be sure to keep let activeFilter = "all"; right after it.

todo.js
const STORAGE_KEY = "todo-tasks";

function load() {
  try {
    const data = localStorage.getItem(STORAGE_KEY);
    return data ? JSON.parse(data) : [];
  } catch (error) {
    return [];
  }
}

function save() {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks));
}

let tasks = load();
  • load() reads the key from storage. If it exists, we convert the text into an array; otherwise we return an empty array (first launch).
  • The try / catch block protects the application: if the data is corrupted or if localStorage is unavailable, we start again from an empty list instead of crashing.
  • let tasks = load(); therefore initializes the state with the tasks already saved.
  • The STORAGE_KEY constant avoids repeating the key name, a classic source of typos.

Why protect the read?

Storage data can be edited by hand in the developer tools, or blocked by certain privacy settings. If JSON.parse receives invalid text, it throws an error that would stop the whole script. Thanks to the try / catch, the application starts anyway, simply with an empty list.

Also note that load() is called only once, at startup, to initialize tasks. After that, the in-memory array is the reference, and save() simply stores it.

Saving after every change

You need to call save() every time the tasks array changes. Replace your actions section with this code, which also adds the new clearCompleted function:

todo.js
// ── 5. Actions ─────────────────────────────
function addTask(text) {
  tasks.push({ id: Date.now(), text: text, done: false });
  save();
  render();
}

function toggleTask(id) {
  const task = tasks.find((t) => t.id === id);
  if (task) {
    task.done = !task.done;
  }
  save();
  render();
}

function deleteTask(id) {
  tasks = tasks.filter((t) => t.id !== id);
  save();
  render();
}

function clearCompleted() {
  tasks = tasks.filter((t) => !t.done);
  save();
  render();
}

The pattern is always the same: 1) modify the data, 2) save, 3) render. Finally, connect the clear button with the other events, before the final render(); call:

todo.js
clearButton.addEventListener("click", clearCompleted);

Why save every time?

The user can close the tab at any moment. If you only saved from time to time, they would lose their latest changes. By saving right after each change, the storage always reflects the real state of the application. The array is small, so this operation is instantaneous.

The clearCompleted function follows the same model as deleteTask: filter keeps only the tasks whose done is false, and the new array replaces the old one.

Check your work

  • Add a few tasks, check one, then reload the page: everything should be kept, including the checked state.
  • Close the tab, reopen todo.html: your tasks are still there.
  • Click Clear completed tasks: only the checked tasks disappear.
  • In the console, type localStorage.getItem("todo-tasks"): you get the JSON text of your tasks.
  • In the developer tools, open the Application (or Storage) tab then Local Storage: you can see the todo-tasks key and its JSON content.

If your tasks still disappear on reload, check that save() is called in every action function, and that the key name is identical everywhere.

Screenshot of the todo.html page in the browser

Common mistakes to avoid

  • Forgetting JSON.stringify: without conversion, localStorage would store the text "[object Object]" instead of your tasks.
  • Forgetting save() in a function: the change would be visible on screen but lost on reload.
  • Keeping the old let tasks = []: the list would start empty on every visit, because load() would never be used.

The complete JavaScript code

Here is the final todo.js file. Compare it with yours to check that everything is in place:

todo.js
// ═══════════════════════════════════════════
//  TODO LIST — todo.js
// ═══════════════════════════════════════════

// ── 1. DOM elements ────────────────────────
const form = document.querySelector("#form");
const field = document.querySelector("#new-task");
const list = document.querySelector("#list");
const counter = document.querySelector("#counter");
const emptyMessage = document.querySelector("#empty-message");
const filterButtons = document.querySelectorAll(".filter");
const clearButton = document.querySelector("#clear-completed");

// ── 2. Saving (localStorage) ───────────────
const STORAGE_KEY = "todo-tasks";

function load() {
  try {
    const data = localStorage.getItem(STORAGE_KEY);
    return data ? JSON.parse(data) : [];
  } catch (error) {
    return [];
  }
}

function save() {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks));
}

// ── 3. Application state ───────────────────
let tasks = load();
let activeFilter = "all";

// ── 4. Rendering ───────────────────────────
function createTask(task) {
  const li = document.createElement("li");
  li.className = "task";
  li.dataset.id = task.id;
  if (task.done) {
    li.classList.add("done");
  }

  const checkbox = document.createElement("input");
  checkbox.type = "checkbox";
  checkbox.checked = task.done;
  checkbox.setAttribute("aria-label", "Mark as completed");

  const text = document.createElement("span");
  text.className = "task__text";
  text.textContent = task.text;

  const deleteButton = document.createElement("button");
  deleteButton.type = "button";
  deleteButton.className = "task__delete";
  deleteButton.textContent = "×";
  deleteButton.setAttribute("aria-label", "Delete task");

  li.append(checkbox, text, deleteButton);
  return li;
}

function visibleTasks() {
  if (activeFilter === "active") {
    return tasks.filter((t) => !t.done);
  }
  if (activeFilter === "completed") {
    return tasks.filter((t) => t.done);
  }
  return tasks;
}

function updateCounter() {
  const remaining = tasks.filter((t) => !t.done).length;
  counter.textContent =
    remaining + (remaining === 1 ? " task remaining" : " tasks remaining");
}

function render() {
  const visible = visibleTasks();

  list.replaceChildren();
  visible.forEach((task) => {
    list.appendChild(createTask(task));
  });

  emptyMessage.hidden = visible.length > 0;
  updateCounter();
}

// ── 5. Actions ─────────────────────────────
function addTask(text) {
  tasks.push({ id: Date.now(), text: text, done: false });
  save();
  render();
}

function toggleTask(id) {
  const task = tasks.find((t) => t.id === id);
  if (task) {
    task.done = !task.done;
  }
  save();
  render();
}

function deleteTask(id) {
  tasks = tasks.filter((t) => t.id !== id);
  save();
  render();
}

function clearCompleted() {
  tasks = tasks.filter((t) => !t.done);
  save();
  render();
}

// ── 6. Events ──────────────────────────────
form.addEventListener("submit", (event) => {
  event.preventDefault();

  const text = field.value.trim();
  if (text === "") return;

  addTask(text);
  field.value = "";
  field.focus();
});

list.addEventListener("click", (event) => {
  const element = event.target.closest(".task");
  if (!element) return;

  const id = Number(element.dataset.id);

  if (event.target.matches(".task__delete")) {
    deleteTask(id);
  } else if (event.target.matches('input[type="checkbox"]')) {
    toggleTask(id);
  }
});

filterButtons.forEach((button) => {
  button.addEventListener("click", () => {
    activeFilter = button.dataset.filter;
    filterButtons.forEach((b) => b.classList.toggle("active", b === button));
    render();
  });
});

clearButton.addEventListener("click", clearCompleted);

// ── 7. Startup ─────────────────────────────
render();

Take the time to reread the whole thing: it always follows the same order, from the most general to the most specific. First the DOM elements, then saving, the state, rendering, actions, events, and finally the startup with render();. This organization into numbered sections will serve as a model for all your future projects.

If your application doesn't work, compare your file with this one section by section, starting from the top: a mistake in a selector or a function name is easier to spot when you reread in order.

Going further

Your project is finished, but you can enrich it with these ideas:

  1. Allow the user to edit a task's text by double-clicking on it.
  2. Add a due date to each task and sort the list by date.
  3. Create a dark mode by redefining the CSS variables in a prefers-color-scheme: dark media query.
  4. Add an appearance animation with @keyframes on new tasks.
  5. Publish your project for free on GitHub Pages or Netlify to share it.
  6. Also save the active filter in localStorage, to get the same view back on every visit.

Key takeaways

  • An application is built around a state (here the tasks array): we modify the data, then redraw the interface.
  • The DOM is built with createElement, and textContent protects against code injection.
  • Event delegation makes it possible to handle clicks on dynamically created elements.
  • forEach, filter and find are the basic tools for working with an array of objects.
  • localStorage with JSON.stringify and JSON.parse lets you keep data between visits.
  • The right reflex for every action: modify, save, render.

Congratulations: you have built a real, complete web application, with a state, dynamic rendering, events and saving. You now have all the basics to launch into your own projects.