Nyx

Chapter 13 · Beyond the DOM

Saving data and smart state

Refresh a page and everything you typed or clicked is gone. In this chapter you'll learn to save data in the visitor's browser so it's still there tomorrow, and to keep your data in a smart state that updates the page by itself and can undo mistakes.

Why pages forget

Variables live only while the page is open. Click +1 a few times, then press Run again (just like refreshing a page):

Clicks: 0

Back to 0. Each time the page loads, the code starts again from the top, and let clicks = 0 starts again too. To keep something, you have to save it somewhere that lasts.

Where the browser keeps data

Every browser has a small store for each website, called localStorage. What you save there stays after a refresh, after closing the browser, even after restarting the computer, until it's deleted.

Kept inHow long it lasts, and who sees it
A variableUntil the page is refreshed or closed.
The browser (localStorage)Until it's deleted. Only on this browser on this computer, and only for your website.
A serverUntil it's deleted. Everywhere: other computers, phones, other people. You learned this in Servers and AJAX.

The browser is perfect for preferences and work in progress: a visitor's name, a "don't show this again" choice, a half-written form, a shopping list.

Not for secrets

Anyone using the same computer can see what's saved, and so can any script on your page. Never save passwords or card numbers in the browser.

Saving and reading: nyx.remember

Give nyx.remember() a name and a value to save. Give it just the name to read the value back:

nyx.remember(save "name",under this name "Asha"this value )Done
nyx.remember("name", "Asha");   // save
nyx.remember("name");           // read: "Asha"

Type your name and press Save. Then press Run again, or even refresh this whole page and come back: your name is still there.

Names are up to you. Use clear ones like "student-name", and use the exact same spelling to read the value back.

When nothing is saved yet

On a visitor's first visit, nothing is saved, so reading gives undefined. Add ?? and a starting value. It means "if there's nothing, use this instead":

const size = nyx.remember("text-size") ?? "medium";
const visits = nyx.remember("visits") ?? 0;

A visit counter that keeps counting across refreshes. Press Run a few times:

Why ?? and not ||? || also replaces 0, false and empty text, which are real saved values. ?? only replaces "nothing".

What you can save

Nyx saves your value as text (in the JSON format from Servers and AJAX) and turns it back when you read it, so it comes back the same type:

ValueCan it be saved?
Text, numbers, true / falseYes: nyx.remember("age", 15) gives back the number 15.
ListsYes: nyx.remember("marks", [90, 85, 77])
ObjectsYes: nyx.remember("profile", { name: "Asha", class: 8 })
DatesThey come back as text, like "2026-11-29T10:15:00.000Z". nyx.date() and nyx.ago() read that text fine.
Functions and page elementsNo. Save the data you need instead, like an element's text. Nyx tells you if you try.

Each website gets about 5 MB, which is plenty for preferences and lists. If it fills up, Nyx tells you.

Deleting: nyx.forget

nyx.forget() deletes a saved value. A "Don't show again" notice stays hidden once it's closed; the second button brings it back:

The library is closed on Saturday.

Close the notice, then press Run: it stays hidden. Visitors can also delete everything a site saved, from their browser's settings, so always have a sensible starting value.

Seeing saved data

You can look inside the browser's store. Open the developer tools (F12), choose the Application tab (Storage in Firefox), then Local storage and this website. Nyx's values have names starting with nyx:, like nyx:student-name, so they never mix with other scripts' data. You can edit or delete them there too.

In plain JavaScript, saving and reading takes a few more steps:

Plain JavaScript

localStorage.setItem("marks", JSON.stringify([90, 85]));
const marks = JSON.parse(localStorage.getItem("marks"));

Turn the list into text yourself, and back again. A typo in the text makes JSON.parse crash.

Nyx

nyx.remember("marks", [90, 85]);
const marks = nyx.remember("marks");

Nyx does the converting, and keeps working even when a browser blocks saving.

Smart state: nyx.state

As pages grow, the same data appears in several places: a score in the header, a progress bar, a "Well done!" message. Each change means updating every place by hand, and it's easy to forget one.

nyx.state() keeps your data in one object, called the state. You describe once how the page should look, using .watch(), and Nyx runs it again whenever the data changes:

Score: 0

  1. nyx.state({ score: 0 })Make a state with one value, score, starting at 0.
  2. game.watch((g) => { ... })Draw the page from the data. It runs straight away, and again after every change. g is the state.
  3. game.score++Just change the data. You never touch the page here: .watch() does that.

The buttons only change the score. The number, the bar and the message all follow by themselves.

Changing state

Change a state exactly like a normal object or list. Every kind of change is noticed:

const cart = nyx.state({ items: [], coupon: "", open: false });

cart.open = true;                                // change a value
cart.items.push({ name: "Notebook", price: 60 }); // add to a list
cart.items[0].price = 55;                        // change something inside
cart.items.splice(0, 1);                         // remove from a list
cart.coupon = "";                                // the same value: nothing happens

Several changes in a row, like everything in one click, are gathered up, and .watch() runs once after them, not once per line. That keeps pages fast.

A state holds plain data

Text, numbers, true/false, lists and objects. Not functions or page elements: keep those in normal variables. And the state itself must be an object in { }: write nyx.state({ count: 0 }), not nyx.state(0).

Undo, redo and reset

A state remembers its last 100 changes, so undo comes free. .canUndo() and .canRedo() tell you whether there's anything to undo or redo, which is handy for greying out buttons:

0

ToolWhat it does
state.undo()Go back one change.
state.redo()Go forward again, after an undo. Making a new change clears the redo steps.
state.canUndo()true if there's something to undo.
state.canRedo()true if there's something to redo.
state.reset()Back to the starting data. Reset can be undone too.

State that survives a refresh

Add { remember: "a name" }, and the state saves itself in the browser after every change, and loads itself back next time. It's nyx.remember() and nyx.state() working together:

const cart = nyx.state({ items: [] }, { remember: "cart" });

A packing list. Add a few things, then press Run again or refresh the page:

    trip.reset() goes back to the starting data, an empty list, and that's saved too. To delete the saved copy completely, use nyx.forget("trip").

    More state tools

    ToolWhat it does
    state.toJSON()A plain copy of the data, not connected to the state. Use it to send to a server: nyx.post("/api/cart", cart.toJSON()).
    const w = state.watch(fn)Gives back a watcher. w.stop() stops it, like the timers in Timers and delays.

    Watch the Output below.

    The watcher printed the start and the first change, but not the last one: it had been stopped. The await nyx.wait() lines give Nyx a moment to run the watcher, because it waits until a batch of changes is finished.

    A state's own tools use these names, so your data can't: watch, undo, redo, canUndo, canRedo, reset and toJSON. Nyx tells you if you try.

    Putting it together

    A homework planner that remembers your tasks, ticks them off, counts what's left and lets you undo:

      1. nyx.state(start, { remember: "homework" })The tasks live in one state, saved in the browser.
      2. item.data("index", i)Each list item remembers its position in the list, so a click knows which task it is.
      3. p.tasks.filter((task) => !task.done).lengthCount the tasks that aren't done. .filter() keeps the items that pass the test; ! means "not".
      4. planner.tasks.push({ text, done: false })Add a task. { text } is short for { text: text }.
      5. task.done = !task.done;Clicking a task flips it between done and not done. The page, the count and the saved copy all follow.

      Common mistakes

      MistakeFix
      Reading a different name than you saved"studentName" and "student-name" are different. Use exactly the same name.
      Getting undefined on the first visitNothing is saved yet. Add a starting value: nyx.remember("visits") ?? 0.
      Saving a passwordNever. Anyone with the computer can read the browser's store.
      Expecting it on another deviceThe browser's store is only on this browser. To share data between devices, save it on a server.
      nyx.state(0)A state is an object: nyx.state({ count: 0 }), then use state.count.
      Updating the page in a click listenerChange the data only, and let .watch() draw the page.
      The page doesn't change after a changeChange the state itself (cart.items.push(...)), not a copy from .toJSON().

      Exercise

      Fill in the blanks, then press Check answers.

      1. Save the text size as "large".

      nyx.("text-size", "large");

      2. Read it back, using "medium" if nothing is saved.

      const size = nyx.remember("text-size")  "medium";

      3. Delete the saved text size.

      nyx.("text-size");

      4. Make a state with a score of 0.

      const game = nyx.({ score: 0 });

      5. Show the score now and after every change.

      game.((g) => nyx("#score").text(g.score));

      6. Go back one change.

      game.();

      7. Make the cart save itself in the browser.

      const cart = nyx.state({ items: [] }, { : "cart" });

      Remember

      Variables are lost on refresh. The browser's store (localStorage) keeps data until it's deleted, on this browser only.
      nyx.remember(name, value) saves; nyx.remember(name) reads; nyx.forget(name) deletes.
      Use ?? for a starting value. Never save passwords.
      nyx.state({ ... }) keeps data in one place. Change it like a normal object.
      .watch() draws the page now and after every change. Change the data; let the watcher update the page.
      .undo(), .redo() and .reset() come free. { remember: "name" } saves the state in the browser.