Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 35 ยท Projects

Project: A Todo App with Runes

Build a complete todo app in Svelte 5 with $state, $derived, a shared class store, components, filters and localStorage persistence, plus a runnable plain-JS demo.

Time to put the pieces together. In this project you will build a todo app: add, complete, edit and delete tasks, filter by status, see how many remain and keep everything after a page reload. It is small enough to finish in one sitting and touches most of what a Svelte app needs: state, derived values, components, props, callbacks, bindings, keyed lists and a bit of browser storage.

The Svelte compiler cannot run here, so the Svelte files are read-only. Below them you get a runnable stand-in: the same logic written as a framework-free store plus a small DOM view, which you can edit and run in the page. Copy the Svelte files into a project made with npx sv create to run the real thing.

What we are building

flowchart TD
  A["todos.svelte.js: the store (state + derived + actions)"] --> B["+page.svelte"]
  B --> C["TodoInput.svelte"]
  B --> D["TodoList.svelte"]
  D --> E["TodoItem.svelte (x N)"]
  B --> F["Filters.svelte"]

One store owns the data; small components display it.

Features: add a todo, toggle done, edit text by double-clicking, delete, filter All/Active/Done, "N items left", clear completed, persistence.

Step 1: the store

Keep the logic in a .svelte.js module so components stay tiny and the rules are testable (see Testing Svelte). A class with $state fields and $derived values is the Svelte 5 pattern:

JavaScript
// src/lib/todos.svelte.js
const KEY = 'svelte-todos';

class TodoStore {
  items = $state([]);
  filter = $state('all'); // 'all' | 'active' | 'done'

  visible = $derived.by(() => {
    if (this.filter === 'active') return this.items.filter((t) => !t.done);
    if (this.filter === 'done') return this.items.filter((t) => t.done);
    return this.items;
  });

  remaining = $derived(this.items.filter((t) => !t.done).length);
  hasDone = $derived(this.items.some((t) => t.done));

  load() {
    try {
      this.items = JSON.parse(localStorage.getItem(KEY) ?? '[]');
    } catch {
      this.items = [];
    }
  }

  save() {
    try {
      localStorage.setItem(KEY, JSON.stringify(this.items));
    } catch {
      /* storage may be unavailable (private mode) */
    }
  }

  add(text) {
    const clean = text.trim();
    if (!clean) return false;
    this.items.push({ id: crypto.randomUUID(), text: clean, done: false });
    return true;
  }

  remove(id) {
    this.items = this.items.filter((t) => t.id !== id);
  }

  clearDone() {
    this.items = this.items.filter((t) => !t.done);
  }
}

export const todos = new TodoStore();

items.push(...) is reactive because $state proxies arrays. visible and remaining are $derived: they recompute only when items or filter change.

Step 2: components

HTML
<!-- src/lib/TodoInput.svelte -->
<script>
  let { onadd } = $props();
  let text = $state('');

  function submit(event) {
    event.preventDefault();
    if (onadd(text)) text = '';
  }
</script>

<form onsubmit={submit}>
  <label>
    <span class="sr-only">New todo</span>
    <input bind:value={text} placeholder="What needs doing?" autocomplete="off" />
  </label>
  <button>Add</button>
</form>
HTML
<!-- src/lib/TodoItem.svelte -->
<script>
  let { todo, onremove } = $props();
  let editing = $state(false);
</script>

<li class:done={todo.done}>
  {#if editing}
    <input
      bind:value={todo.text}
      onblur={() => (editing = false)}
      onkeydown={(e) => (e.key === 'Enter' || e.key === 'Escape') && (editing = false)}
    />
  {:else}
    <label>
      <input type="checkbox" bind:checked={todo.done} />
      <span ondblclick={() => (editing = true)}>{todo.text}</span>
    </label>
    <button type="button" onclick={() => (editing = true)} aria-label="Edit {todo.text}">Edit</button>
    <button type="button" onclick={onremove} aria-label="Delete {todo.text}">Delete</button>
  {/if}
</li>

<style>
  .done span { text-decoration: line-through; opacity: 0.6; }
</style>

The todo prop is an object from the store's $state array, so it is a deep proxy: bind:checked={todo.done} and bind:value={todo.text} change the store's data directly, with no callbacks needed. (This works because the object lives in a shared module store. For state owned by a parent component, prefer callback props or $bindable so ownership stays clear.) The Edit button gives keyboard users what double-click gives mouse users, in line with Svelte Accessibility.

HTML
<!-- src/lib/Filters.svelte -->
<script>
  let { value = $bindable(), count, hasDone, onclear } = $props();
  const options = [['all', 'All'], ['active', 'Active'], ['done', 'Done']];
</script>

<footer>
  <span>{count} {count === 1 ? 'item' : 'items'} left</span>
  <div role="group" aria-label="Filter">
    {#each options as [key, label] (key)}
      <button type="button" aria-pressed={value === key} onclick={() => (value = key)}>{label}</button>
    {/each}
  </div>
  {#if hasDone}<button type="button" onclick={onclear}>Clear completed</button>{/if}
</footer>

Step 3: the page

HTML
<!-- src/routes/+page.svelte -->
<script>
  import { onMount } from 'svelte';
  import { todos } from '$lib/todos.svelte.js';
  import TodoInput from '$lib/TodoInput.svelte';
  import TodoItem from '$lib/TodoItem.svelte';
  import Filters from '$lib/Filters.svelte';

  onMount(() => todos.load());   // runs only in the browser

  // save whenever anything inside items changes (text, done, add, remove)
  let loaded = false;
  $effect(() => {
    JSON.stringify(todos.items); // read everything so the effect tracks it
    if (loaded) todos.save();
    loaded = true;
  });
</script>

<svelte:head><title>Todos ({todos.remaining} left)</title></svelte:head>

<h1>Todos</h1>
<TodoInput onadd={(text) => todos.add(text)} />

{#if todos.items.length === 0}
  <p>Nothing to do. Enjoy!</p>
{:else}
  <ul>
    {#each todos.visible as todo (todo.id)}
      <TodoItem {todo} onremove={() => todos.remove(todo.id)} />
    {/each}
  </ul>
  <Filters bind:value={todos.filter} count={todos.remaining} hasDone={todos.hasDone} onclear={() => todos.clearDone()} />
{/if}

Points worth noticing:

  • Load in onMount, not at the top level: localStorage does not exist on the server, and SvelteKit renders on the server first.
  • The $effect reads JSON.stringify(todos.items) to subscribe to deep changes, then saves. The loaded guard avoids overwriting stored data with the empty initial list.
  • The list is keyed by todo.id, so items keep their editing state when the filter or order changes.

The runnable version

The stand-in below implements the same store (add, toggle, edit, delete, filter, remaining count) in plain JavaScript with a tiny render() function in place of Svelte's reactivity. Edit the code, then run it.

Todo app (plain JavaScript stand-in)

Double-click a todo to rename it. Notice how much of the code is the render() function pushing state to the DOM: in Svelte that whole function disappears, because the template is the description of the output and the compiler generates the updates.

Step 4: test the store

The store has real rules (no empty todos, derived counts), so it deserves unit tests. Plain logic like this is also easy to check right here:

JS Checking the store rules

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Ideas to extend it

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why load from localStorage in onMount instead of at the top level of the script?

    onMount runs only in the browser after the component is mounted, so browser-only APIs are safe there.
  2. 2. Why is the each block keyed with todo.id?

    Keyed blocks move and reuse nodes by identity instead of by position.
  3. 3. What does $derived.by do in the store?

    $derived.by takes a function for multi-statement derivations; the result is recalculated only when its dependencies change.
  4. 4. Why put the logic in todos.svelte.js instead of in the page?

    Separating logic from presentation makes both simpler and the store reusable across components.

Summary

  • A class with $state fields and $derived values makes a clean, testable store in a .svelte.js file.
  • Small components (TodoInput, TodoItem, Filters) receive data as props and report actions with callback props; $bindable and bind: handle two-way cases.
  • Load browser-only data in onMount; save with an $effect that reads the data it wants to track.
  • Keyed {#each} blocks keep item state stable across filtering.

Next: Project: Live Search