NarraLeaf

Store Data

Use Persistent for values that must survive scene changes and be included in saves. story.createPersistent() creates and registers the namespace in one call.

import { Story } from "narraleaf-react";

const story = new Story("my-story");

const player = story.createPersistent("player", {
    name: "Alex",
    coins: 0,
    hasKey: false,
    startedAt: new Date(),
});

If you construct Persistent yourself, register it before the story runs.

import { Persistent } from "narraleaf-react";

const player = new Persistent("player", { coins: 0 });
story.registerPersistent(player);

Change and display values

set() and assign() create story actions. get() creates a dynamic Word that reads the latest value when the line appears.

scene.action([
    player.set("coins", 50),
    player.set("coins", (coins) => coins + 10),
    player.assign({ hasKey: true }),
    alice.say`You have ${player.get("coins")} coins.`,
]);

Use equals, isTrue, isFalse, and evaluate inside conditions.

Condition.If(player.evaluate("coins", (coins) => coins >= 50), [
    alice.say("You have enough coins."),
]);

Stored values may contain strings, numbers, booleans, plain objects, arrays, null, undefined, and Date. Do not store class instances, functions, DOM nodes, or circular objects.

Save the current game

serialize() returns a SavedGame object. Store the whole object, not only the persistent namespace.

import { useLiveGame } from "narraleaf-react";

function SaveButton() {
    const liveGame = useLiveGame();

    function save() {
        const data = liveGame.serialize();
        localStorage.setItem("save-slot-1", JSON.stringify(data));
    }

    return <button onClick={save}>Save</button>;
}

Load a save

Parse the stored object and pass it to deserialize(). Loading replaces the current runtime state.

import type { SavedGame } from "narraleaf-react";

function load() {
    const raw = localStorage.getItem("save-slot-1");
    if (!raw) return;

    const data = JSON.parse(raw) as SavedGame;
    liveGame.deserialize(data);
}

Treat localStorage and network data as untrusted in production. Validate its shape and catch parse or compatibility errors. See Save System with localStorage for a complete example.

On this page