Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 39 ยท Projects

Project: To-Do App with a Mock Backend

Build a to-do app on an in-memory REST-style API: CRUD with fetch, optimistic updates with rollback, a request log and error toasts. Compare the two update styles live.

Reading data is only half of AJAX. Real applications also change data: add a task, tick it off, delete it. Each change is a request that takes time and may fail, and that raises a question every interface has to answer: what should the screen show while the server is thinking?

There are two honest answers. The cautious one is to wait: show a "saving" state and update the screen only after the server confirms. The fast one is to be optimistic: update the screen immediately, assume success, and undo the change if the server says no. Messaging and social apps feel instant because they do the second. In this project you build both and flip between them with a checkbox.

The backend is a pretend one. A function named mockFetch behaves like a small REST API held in memory: it answers GET, POST, PATCH and DELETE on /api/todos with real Response objects, waits 700 ms so you can feel the delay, and can be told to fail the next write. Prerequisites are sending data with fetch, error handling and rendering API data.

The API we are talking to

A REST-style API maps four actions onto HTTP methods and one URL pattern, and uses status codes to say what happened.

Action Request Success answer
List all GET /api/todos 200 and an array
Create POST /api/todos with { "title": "..." } 201 and the new todo (with its id)
Update PATCH /api/todos/2 with { "done": true } 200 and the updated todo
Delete DELETE /api/todos/2 204 and no body

Failures use 4xx (your request was wrong: 404 no such todo, 422 invalid title) or 5xx (the server failed). Run this console example to watch the whole API from the outside before we put a screen on top of it. Notice that the DELETE answer has an empty body, so calling .json() on it would throw.

JS Exploring the mock API

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

No output.

Two server habits are visible here and worth copying. The server validates the title itself (422), because client-side checks can be bypassed. And it returns the saved record (201/200 with the todo), so the client can adopt the server's version, including the id the server assigned, instead of guessing.

The optimistic pattern in isolation

Before adding a screen, look at the logic on its own. An optimistic update has four steps: remember the old value, apply the change locally, send the request, and on failure roll back to what you remembered.

sequenceDiagram
  participant U as User
  participant UI as Screen
  participant S as Server
  U->>UI: ticks a checkbox
  UI->>UI: show the change at once, mark as pending
  UI->>S: PATCH /api/todos/2
  alt success
    S-->>UI: 200 and the saved todo
    UI->>UI: replace local data with the server's version
  else failure
    S-->>UI: 500 and an error
    UI->>UI: roll back, show an error message
  end

Optimistic updates show the result first and reconcile with the server afterwards.

The console version below uses no screen. The fake save rejects any title containing the word "bad", and we log the local state at each step so you can see the change appear and then disappear.

JS Optimistic update and rollback, step by step

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

No output.

The local data changes before the await. That is the entire trick, and also its risk: between "applied" and "confirmed" the screen shows something the server may not have. That is why we mark the item as pending and why rollback must be reliable.

The complete app

Now the screen. Try the following, with Optimistic updates ticked first:

  1. Add a task. It appears immediately, slightly dimmed and marked "saving...", and becomes normal 700 ms later when the server answers (look at the request log under the list).
  2. Press Make the next change fail, then tick a task. The checkbox flips at once, then flips back, and a message explains why.
  3. Untick Optimistic updates and repeat. Now nothing changes on screen until the server confirms, and a failed change never appears at all.
  4. Delete a task with the failure switch on: in optimistic mode the row vanishes and then returns to its old position.
To-do app with a mock backend

Reading the code

One api() function for every request. It builds the fetch options (method, JSON headers, JSON body), turns HTTP failures into exceptions, and treats 204 specially because there is no body to parse. Every operation below uses it, so error handling lives in one place.

Pending items. An item whose save is in flight has pending: true. It is dimmed, labelled "saving...", and ignores further clicks. This avoids a nasty class of bugs: two quick toggles on the same item would send two requests whose answers can arrive in either order. Ignoring input until the first save settles is the simplest correct rule. Notice that we use aria-disabled and ignore the event rather than the disabled attribute, because a disabled control loses keyboard focus and our list is rebuilt after every change.

Temporary ids. A task created optimistically has no real id yet, so it gets tmp-1, tmp-2 and so on. When the server answers, the temporary object is replaced by the one the server returned, which carries the real id. If the request fails, the temporary object is removed.

Rollback needs a snapshot. Each operation remembers exactly what it changed (before, index, or the temporary object) and restores exactly that. It never reloads everything, and it does not touch other items that may have changed in the meantime. Deleting remembers the index, so a failed delete puts the row back where it was (an approximation if other rows moved meanwhile, which is acceptable here).

Failures are loud. Every error produces a message in a role="alert" region, which screen readers announce at once, and tells the user what happened to their change ("The change was undone"). A silent rollback would look like a bug.

In pessimistic mode a failed change simply never appears, and the message says so. In optimistic mode the user briefly saw something that was not true. The right choice depends on the stakes: ticking a to-do is cheap to undo and fails rarely, so optimistic is a good fit; submitting a payment should wait for the server.

Ideas to extend it

  1. Rename tasks with a PATCH that sends the new title, with the same snapshot-and-rollback approach.
  2. Retry a failed change from the toast instead of only undoing it (retries and backoff).
  3. Use AbortController to cancel an in-flight request when the user deletes the item (cancelling requests).
  4. Filter the list (all, active, done) as derived data.
  5. Move the API calls into a client module with timeouts and hooks, as in the next project.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What defines an optimistic update?

    Optimistic means assuming success: show the result first, then reconcile with the server, rolling back on failure.
  2. 2. Why does the DELETE helper return null for status 204 instead of calling response.json()?

    204 No Content means success with an empty body. Calling json() on an empty body fails with a syntax error.
  3. 3. What should the app do with the temporary object (tmp-1) when the server answers a successful POST?

    The server owns ids and other generated fields, so the client adopts the saved record that comes back.
  4. 4. Why does the app ignore a second click on an item while its first save is still pending?

    Overlapping updates to the same item create ordering problems. Waiting for the first save to settle is the simplest rule that keeps client and server consistent.
  5. 5. Which kind of action is a poor candidate for optimistic updates?

    Optimistic updates suit cheap, rarely failing, easily undone actions. A payment should wait for the server's confirmation before telling the user it worked.

Summary

  • A REST-style API maps create, read, update and delete onto POST, GET, PATCH and DELETE, and uses status codes (201, 204, 404, 422, 500) to describe the outcome.
  • Wrap fetch in one api() helper that sets JSON headers, throws on HTTP errors and handles empty 204 bodies.
  • Pessimistic updates wait for the server; optimistic updates apply the change first, remember a snapshot, and roll back on failure.
  • Mark in-flight items as pending, ignore input on them, use temporary ids for new items and replace them with the server's record.
  • Report every failure in an alert region and say what happened to the user's change.
  • Choose optimistic updates for cheap, reversible actions and pessimistic ones for actions with real consequences.

Next: Project: A Reusable API Client