Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 39 ยท Projects and Practice

Project: A Notes App

Build a notes app step by step: plan the routes and services, store notes in a tracked service with persistence, add search and pinning, and verify the core logic.

Time to put the chapter together. In this project you build a notes app: a list of notes, a page to read and edit one, search, pinning, and persistence in the browser. It exercises everything from the last few lessons: a service shared by many parts of the app, tracked state, derived getters, collections and a design that is easy to test.

Real Ember vs stand-in. The site cannot run an Ember app, so the Ember files below are real code shown read-only, and the heart of the app (the notes service) is also given as a plain-JavaScript program you can run and extend here. Build the Ember version on your own machine with ember new notes-app and copy the files in.

What we are building

Feature Where it lives
list all notes, pinned first, with a search box notes route + NotesList component
open a note and edit its title and text notes.note route + NoteEditor component
create and delete notes notes service methods
save to the browser and restore on reload notes service + storage
show how many notes match derived getter

Step 1: plan the routes

flowchart LR
  A["/ (application)"] --> B["/notes (list + search)"]
  B --> C["/notes/:id (editor)"]
  A --> D["/about"]

Two levels: the list stays visible while one note is open.

app/router.js

JavaScript
import EmberRouter from '@ember/routing/router';
import config from 'notes-app/config/environment';

export default class Router extends EmberRouter {
  location = config.locationType;
  rootURL = config.rootURL;
}

Router.map(function () {
  this.route('notes', function () {
    this.route('note', { path: '/:note_id' });
  });
  this.route('about');
});

Step 2: the note model and the service

A note is a small class with tracked fields, so editing a title re-renders only what shows that title.

app/utils/note.js

JavaScript
import { tracked } from '@glimmer/tracking';

export default class Note {
  @tracked title;
  @tracked body;
  @tracked pinned;

  constructor({ id, title = 'Untitled', body = '', pinned = false, updatedAt = Date.now() }) {
    this.id = id;
    this.title = title;
    this.body = body;
    this.pinned = pinned;
    this.updatedAt = updatedAt;
  }

  toJSON() {
    return {
      id: this.id,
      title: this.title,
      body: this.body,
      pinned: this.pinned,
      updatedAt: this.updatedAt,
    };
  }
}

The service owns the collection, search state, persistence and the derived list:

app/services/notes.js

JavaScript
import Service from '@ember/service';
import { tracked } from '@glimmer/tracking';
import { TrackedArray } from 'tracked-built-ins';
import Note from 'notes-app/utils/note';

const KEY = 'notes-app:v1';

export default class NotesService extends Service {
  @tracked query = '';
  all = new TrackedArray();
  #nextId = 1;

  constructor() {
    super(...arguments);
    this.load();
  }

  get visible() {
    const q = this.query.trim().toLowerCase();
    return this.all
      .filter((n) => !q || n.title.toLowerCase().includes(q) || n.body.toLowerCase().includes(q))
      .toSorted((a, b) => Number(b.pinned) - Number(a.pinned) || b.updatedAt - a.updatedAt);
  }

  find(id) {
    return this.all.find((n) => String(n.id) === String(id));
  }

  create() {
    const note = new Note({ id: this.#nextId++ });
    this.all.push(note);
    this.save();
    return note;
  }

  remove(id) {
    const index = this.all.findIndex((n) => String(n.id) === String(id));
    if (index !== -1) this.all.splice(index, 1);
    this.save();
  }

  save() {
    try {
      localStorage.setItem(KEY, JSON.stringify(this.all.map((n) => n.toJSON())));
    } catch {
      // storage unavailable: the app still works for this session
    }
  }

  load() {
    try {
      const saved = JSON.parse(localStorage.getItem(KEY) ?? '[]');
      saved.forEach((data) => this.all.push(new Note(data)));
      this.#nextId = Math.max(0, ...saved.map((n) => n.id)) + 1;
    } catch {
      // corrupt data: start empty
    }
  }
}

visible is a plain getter that reads query and every note's tracked fields, so the list reorders when you pin a note or change its title, with no extra code.

Step 3: the routes and components

app/routes/notes/note.js

JavaScript
import Route from '@ember/routing/route';
import { service } from '@ember/service';

export default class NotesNoteRoute extends Route {
  @service notes;
  @service router;

  model({ note_id }) {
    const note = this.notes.find(note_id);
    if (!note) {
      this.router.replaceWith('notes');
    }
    return note;
  }
}

app/components/note-editor.gjs

JavaScript
import Component from '@glimmer/component';
import { service } from '@ember/service';
import { action } from '@ember/object';
import { on } from '@ember/modifier';

export default class NoteEditor extends Component {
  @service notes;
  @service router;

  @action update(field, event) {
    this.args.note[field] = event.target.value;
    this.args.note.updatedAt = Date.now();
    this.notes.save();
  }

  @action togglePin() {
    this.args.note.pinned = !this.args.note.pinned;
    this.notes.save();
  }

  @action remove() {
    this.notes.remove(this.args.note.id);
    this.router.transitionTo('notes');
  }

  <template>
    <input data-test-title value={{@note.title}} {{on "input" (fn this.update "title")}} />
    <textarea data-test-body {{on "input" (fn this.update "body")}}>{{@note.body}}</textarea>
    <button type="button" data-test-pin {{on "click" this.togglePin}}>
      {{if @note.pinned "Unpin" "Pin"}}
    </button>
    <button type="button" data-test-delete {{on "click" this.remove}}>Delete</button>
  </template>
}

(fn comes from @ember/helper and must be imported in a .gjs file.)

Step 4: run the logic

The Ember pieces are thin because the service holds the rules. Here is the same service as plain JavaScript with an in-memory storage, so you can run it, see searching and sorting work, and check persistence across a "reload".

JS The notes service, runnable

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

No output.

Notice the * marking the pinned note moving to the top, the search matching text in titles and bodies, and the new id continuing after the reload.

Step 5: extend the app

You now have a working structure. Practice by adding these, thinking each time about where the change belongs:

  1. Sort options (by title, by date): add a tracked sortBy to the service and use it in visible.
  2. Tags: add @tracked tags = new TrackedSet() to Note, and a tag filter next to the search box.
  3. Word count under the editor: a getter on Note that splits body.
  4. Undo delete: keep the removed note for five seconds and let the notifications service offer "Undo" (see Building Your Own App Services).
  5. Autosave indicator: show "Saved" a moment after the last edit, with a timer cleaned up in a destructor.
  6. Tests: write the unit tests for the service and an acceptance test for creating and pinning a note. The test-suite project walks through exactly this.

Common mistakes in this project

  • Putting search state in the list component. The service is better if the query must survive navigation between routes.
  • Mutating all without a tracked collection (so the list does not update). TrackedArray solves it; with a plain array you would reassign.
  • Saving on every keystroke without thinking: fine for localStorage, but for a network call you would debounce.
  • Forgetting that the route's model runs again when the URL changes, so handle "note not found" there.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is search text kept in the notes service rather than in the list component?

    A component's state disappears when it is destroyed. Shared, long-lived state belongs in a service.
  2. 2. What makes the visible list reorder when a note is pinned?

    The getter reads tracked fields while computing, so changing one invalidates the result automatically.
  3. 3. In the route's model hook, what should happen when the note id does not exist?

    A redirect keeps the user in a valid place, and replaceWith avoids a broken history entry.
  4. 4. What does the service do with corrupt saved data?

    Persistence code must tolerate bad or missing data; falling back to a clean state keeps the app usable.

Summary

  • Plan routes first, then put shared state and rules in a service.
  • A note is a class with tracked fields; the list is a tracked collection; the visible list is a derived getter.
  • Persist in a try/catch-guarded storage call and restore in the constructor.
  • Keep components thin: they bind events to service methods.
  • Extend the project with sorting, tags, undo and tests to practice each concept.

Next: Project: A Task Board