NarraLeaf

useLiveGame

The useLiveGame hook, which returns the LiveGame instance for reading story services, the current scene, and player preferences.

You can access the live game object using this hook.

Note: this hook can only be used in a component that is a descendant of GameProvider.

function useLiveGame(): LiveGame;

A LiveGame carries three properties — game, events and story — and everything else it offers is a method. The scene the story is in comes from getLastScene(), and the player's preferences belong to the Game it is running (liveGame.game.preference).

Usage

import {useLiveGame} from "narraleaf-react";
function myComponent() {
    const liveGame = useLiveGame();

    useEffect(() => {
        // Story services
        const gallery = liveGame.story?.getService<Gallery>("gallery");

        // The scene the story is in
        const currentScene = liveGame.getLastScene();

        // Player preferences live on the Game, not on the LiveGame
        const cps = liveGame.game.preference.getPreference("cps");
    }, [liveGame]);
}

Common Use Cases

Accessing Services

function GalleryComponent() {
    const liveGame = useLiveGame();
    
    const gallery = liveGame.story?.getService<Gallery<{timestamp: number}>>("gallery");
    
    if (gallery) {
        const allItems = gallery.$getAll();
        return (
            <div>
                {Object.keys(allItems).map(name => (
                    <div key={name}>{name}</div>
                ))}
            </div>
        );
    }
    
    return null;
}

Accessing Game State

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

    return (
        <div>
            <p>Current Scene: {liveGame.getLastScene()?.config.name}</p>
            <p>Playing: {String(liveGame.isPlaying())}</p>
        </div>
    );
}

On this page