Skip to content

Page-level data

Page data is a persistent data channel keyed by a name, with no DOM element required. Good for counters, vote tallies, link trackers, anything page-shaped instead of element-shaped.

playhtml.createPageData(name, default) returns a channel handle:

const counter = playhtml.createPageData("my-counter", { count: 0 });
counter.setData((draft) => { draft.count += 1; });
counter.onUpdate((data) => { /* re-render */ });

Channels can also hold a primitive value. Pass the next value directly or return the next value from a functional update:

const viewCount = playhtml.createPageData("viewCount", 0);
viewCount.setData((value) => value + 1);

For object and array channels, function updates are mutators: edit the draft in place and ignore its return value. For primitive channels, the function’s return value becomes the next stored value.

The vanilla channel handle exposes four methods (usePageData wraps these for you):

  • getData(): read the current value synchronously.
  • setData(value | updater): write. Pass a replacement value, mutate an object/array draft in place, or return the next primitive value from an updater; see data essentials.
  • onUpdate(cb): subscribe to changes. Returns an unsubscribe function.
  • destroy(): detach the channel and its observers. Call this when the channel is no longer needed (e.g. on teardown) to avoid leaking the subscription.

When you should reach for createPageData vs. element data, presence, or events: see the decision table on data essentials.

Page data is room-scoped, like element data. On a single-page app, when navigation changes the room the channel resets to the new room: it reads its default until re-seeded. A channel handle you hold across the navigation stays usable (it keeps writing and notifying). Navigation that doesn’t change the room leaves the data untouched. See Navigation & SPAs.