Skip to content

Checkpoint: Notifications

The Course
•
20 min study

Transfer the reducer and controller patterns

A notification model has records with id and read fields. Write reduceInbox(state, action) supporting markRead by id and clearRead. markRead returns a new list with the chosen record read; a missing id changes no record values. clearRead removes read records. Unknown actions throw an error. The input state is an array of already-valid records.

The test checks unchanged input, repeated markRead, a missing id, empty input, clearing an all-read inbox and an unknown action. Predict each of those lines before writing the reducer. Keep printing, storage, and network requests outside the reducer, and decide which unchanged records may remain shared.

Then wrap it in a small controller, createInbox({ items, save, render }), whose dispatch(action) applies the reducer, renders at once with the note "saving", and awaits the injected save(state). If the save fulfills, render again with "saved". If it rejects, roll back to the state before the action and render it with "not saved: " plus the error message, so the screen never claims a change that was not stored. Test it with deferred saves, so your test, not a timer, decides when each save settles.

Predict and trace

Write the output before running. Follow the values through each call; if your prediction differs, identify the first step that surprised you.

Predict, then run JavaScript
const before = [{ id: "a", read: false }];
const after = before.map(item => ({ ...item, read: true }));

console.log(before[0].read);
console.log(after[0].read);
Check your prediction
Text
false
true

Copying the changed record preserves the earlier snapshot.

Acceptance cases before you code

Write the expected render log for these cases before coding. The pending-save case is the one a synchronous test cannot reach.

Case to tryWhat your result should demonstrate
markRead "a", observed while its save is still pendingThe screen already shows a:read (saving) and exactly one save has started
That save fulfillsA second render with the note saved
clearRead, then its save rejects with offlineThe list renders empty, then rolls back to both records with not saved: offline
The original items array afterwardsStill a:new b:read: neither the reducer nor the rollback edited it

When everything passes, delete the line state = previous; and confirm the rejected case now leaves empty on screen. Restore it and explain in one sentence why the rollback must restore the previous state rather than re-running the reducer.

Build it yourself

Exercise

Checkpoint: Notifications: practice

Write both pieces: reduceInbox and createInbox. The test at the bottom checks the reducer on its own first, then drives the controller with deferred saves. It should print:

Text
markRead a: a:read b:read
markRead a again: a:read b:read
missing id: a:new b:read
clearRead on empty: empty
clearRead when all read: empty
unchanged record shared: true
unknown action: Unknown action: archive
a:read b:read (saving)
while saving: 1 save pending
a:read b:read (saved)
empty (saving)
a:read b:read (not saved: offline)
input unchanged: a:new b:read
Your working space JavaScript
async function main() {
  function reduceInbox(state, action) {
    // Handle "markRead" (by id) and "clearRead"; throw for anything else.
    return state;
  }

  function createInbox({ items, save, render }) {
    let state = items;
    return {
      async dispatch(action) {
        state = reduceInbox(state, action);
        render(state, "saving");
        // Placeholder: ignores the outcome. Render "saved", or roll back on failure.
        await save(state).catch(() => {});
      }
    };
  }

  function deferred() {
    let resolve;
    let reject;
    const promise = new Promise((yes, no) => {
      resolve = yes;
      reject = no;
    });
    return { promise, resolve, reject };
  }

  const show = list =>
    list.length === 0 ? "empty" : list.map(item => `${item.id}:${item.read ? "read" : "new"}`).join(" ");
  const items = [
    { id: "a", read: false },
    { id: "b", read: true }
  ];

  // ---- reducer checks ----
  const once = reduceInbox(items, { type: "markRead", id: "a" });
  console.log(`markRead a: ${show(once)}`);
  console.log(`markRead a again: ${show(reduceInbox(once, { type: "markRead", id: "a" }))}`);
  console.log(`missing id: ${show(reduceInbox(items, { type: "markRead", id: "zz" }))}`);
  console.log(`clearRead on empty: ${show(reduceInbox([], { type: "clearRead" }))}`);
  console.log(`clearRead when all read: ${show(reduceInbox(once, { type: "clearRead" }))}`);
  console.log(`unchanged record shared: ${once[1] === items[1]}`);
  try {
    reduceInbox(items, { type: "archive" });
    console.log("unknown action: no error");
  } catch (error) {
    console.log(`unknown action: ${error.message}`);
  }

  // ---- controller checks ----
  const log = [];
  const saves = [];
  const inbox = createInbox({
    items,
    save() {
      saves.push(deferred());
      return saves.at(-1).promise;
    },
    render(state, note) {
      log.push(`${show(state)} (${note})`);
    }
  });

  const first = inbox.dispatch({ type: "markRead", id: "a" });
  log.push(`while saving: ${saves.length} save pending`);
  saves[0].resolve();
  await first;

  const second = inbox.dispatch({ type: "clearRead" });
  saves[1].reject(new Error("offline"));
  await second;

  console.log(log.join("\n"));
  console.log(`input unchanged: ${show(items)}`);
}

main();
Hint 1: the idea

Two rules do all the work. The reducer never edits what it was given: it returns a new array, copying only the record that changes. And dispatch has to remember the state from before the action, because a rejected save means the stored data still looks like that. The first render happens before await; everything after await runs only once the test settles the deferred save.

Hint 2: a first step

Write the reducer first, one case at a time, and run after each: markRead, then clearRead, then the default. Adding the default before clearRead would make the clearRead checks throw. When all seven reducer lines match, make dispatch render "saved" after the awaited save succeeds, run again, and look at what the rejected clearRead leaves on screen.

Show one solution
JavaScript
async function main() {
  function reduceInbox(state, action) {
    switch (action.type) {
      case "markRead":
        return state.map(item => (item.id === action.id ? { ...item, read: true } : item));
      case "clearRead":
        return state.filter(item => !item.read);
      default:
        throw new Error(`Unknown action: ${action.type}`);
    }
  }

  function createInbox({ items, save, render }) {
    let state = items;

    return {
      async dispatch(action) {
        const previous = state;
        state = reduceInbox(state, action);
        render(state, "saving");
        try {
          await save(state);
          render(state, "saved");
        } catch (error) {
          state = previous; // roll back: the screen must match what is stored
          render(state, `not saved: ${error.message}`);
        }
      }
    };
  }

  function deferred() {
    let resolve;
    let reject;
    const promise = new Promise((yes, no) => {
      resolve = yes;
      reject = no;
    });
    return { promise, resolve, reject };
  }

  const show = list =>
    list.length === 0 ? "empty" : list.map(item => `${item.id}:${item.read ? "read" : "new"}`).join(" ");
  const items = [
    { id: "a", read: false },
    { id: "b", read: true }
  ];

  // ---- reducer checks ----
  const once = reduceInbox(items, { type: "markRead", id: "a" });
  console.log(`markRead a: ${show(once)}`);
  console.log(`markRead a again: ${show(reduceInbox(once, { type: "markRead", id: "a" }))}`);
  console.log(`missing id: ${show(reduceInbox(items, { type: "markRead", id: "zz" }))}`);
  console.log(`clearRead on empty: ${show(reduceInbox([], { type: "clearRead" }))}`);
  console.log(`clearRead when all read: ${show(reduceInbox(once, { type: "clearRead" }))}`);
  console.log(`unchanged record shared: ${once[1] === items[1]}`);
  try {
    reduceInbox(items, { type: "archive" });
    console.log("unknown action: no error");
  } catch (error) {
    console.log(`unknown action: ${error.message}`);
  }

  // ---- controller checks ----
  const log = [];
  const saves = [];
  const inbox = createInbox({
    items,
    save() {
      saves.push(deferred());
      return saves.at(-1).promise;
    },
    render(state, note) {
      log.push(`${show(state)} (${note})`);
    }
  });

  const first = inbox.dispatch({ type: "markRead", id: "a" });
  log.push(`while saving: ${saves.length} save pending`);
  saves[0].resolve();
  await first;

  const second = inbox.dispatch({ type: "clearRead" });
  saves[1].reject(new Error("offline"));
  await second;

  console.log(log.join("\n"));
  console.log(`input unchanged: ${show(items)}`);
}

main();
Text
markRead a: a:read b:read
markRead a again: a:read b:read
missing id: a:new b:read
clearRead on empty: empty
clearRead when all read: empty
unchanged record shared: true
unknown action: Unknown action: archive
a:read b:read (saving)
while saving: 1 save pending
a:read b:read (saved)
empty (saving)
a:read b:read (not saved: offline)
input unchanged: a:new b:read

markRead maps over the list and spreads only the matching record, so a missing id returns new copies of nothing changed and the untouched b record is the same object as before (unchanged record shared: true), which is safe because nobody edits it. Repeating markRead gives the same result, and clearRead on an empty or all-read list returns empty without a special case, because filter handles both. The default case throws with the action's name, so a typo is caught instead of silently ignored.

In the controller, the first render runs before await save(state), which is why the test can observe a:read (saving) while the save is still pending: the deferred promise holds dispatch at its await until the test calls resolve. On rejection, state = previous restores the exact array from before clearRead; re-running some inverse action could not bring back records that were removed. The reducer stays pure and synchronous, and the controller owns the asynchronous part, so items is never edited and the reducer can still be tested on its own.

Test a changed requirement

Two saves can now overlap: dispatch twice without settling the first. Decide what a rollback of the first should do once the second has already changed the list, and write the deferred schedule that tests it.

Explain before moving on

Which action is safe to repeat? Why does the rollback test need a deferred save rather than one that rejects immediately?

Was this article helpful?

Your response is saved on this device.