Browse recipes

Persist a local value

Follow one theme preference through its browser-storage lifetime.

Table of contents

APIs used

mount
Starts a Valyrian.js application on a DOM target.
StorageType
Identifies the native storage strategies accepted by createNativeStore.
createNativeStore
Creates a named store with the selected storage type, or returns it when reuse is enabled.

Run this recipe

Starting project
Use the local TSX and ESM project from Stage 1 with Valyrian.js installed and its ESM browser build configured.
File
Replace src/client-entry.tsx with this recipe snippet.
Run
Run npm run build, serve public with npx --yes serve@14.2.5 public --listen 8000, open http://localhost:8000 and use the example's visible controls.
Observable result
The view displays the saved dark theme even though the key is removed before cleanup.

Starting point

Start with a dark theme preference that should survive a page reload.

Steps

Write the theme with set, read it with get, remove it with delete, render the captured value and clean up the store.

ts
import { mount } from "valyrian.js";
import { StorageType, createNativeStore } from "valyrian.js/native-store";

const preferences = createNativeStore("preferences", {}, StorageType.Local);

preferences.set("theme", "dark");
const savedTheme = preferences.get("theme");
preferences.delete("theme");

mount("body", () => `Saved theme: ${savedTheme}`);
preferences.cleanup();

Result

The view displays the saved dark theme even though the key is removed before cleanup.

Continue