Skip to content
dojo-state logo

Dojo.js State Management

dojo-state

Use when managing game state with Zustand in dojo.js. Triggers: dojo state, zustand dojo, game state, createDojoStore, optimistic update, getEntity, mergeEntities, state management, revert transaction

SKILL.md

Full skill instructions

Dojo.js State Management

When to Use

Use this skill when:

  • Setting up the Zustand store for game state
  • Accessing entities from the store
  • Implementing optimistic updates
  • Working with historical entity data

Store Setup

import { createDojoStore } from "@dojoengine/​sdk/​react";
import type { GameState } from "@dojoengine/​state/​zustand";

// Create typed store
const useDojoStore = createDojoStore<typeof schema>();

GameState Interface

interface GameState<T> {
    entities: Record<string, ParsedEntity<T>>;
    historical_entities: Record<string, ParsedEntity<T>[]>;
    pendingTransactions: Record<string, PendingTransaction>;

    // Entity operations
    setEntities: (entities: ParsedEntity<T>[]) => void;
    mergeEntities: (entities: ParsedEntity<T>[]) => void;
    updateEntity: (entity: Partial<ParsedEntity<T>>) => void;

    // Historical operations
    setHistoricalEntities: (entities: ParsedEntity<T>[]) => void;
    mergeHistoricalEntities: (entities: ParsedEntity<T>[]) => void;

    // Optimistic updates
    applyOptimisticUpdate: (transactionId: string, updateFn: (draft) => void) => void;
    revertOptimisticUpdate: (transactionId: string) => void;
    confirmTransaction: (transactionId: string) => void;

    // Queries
    getEntity: (entityId: string) => ParsedEntity<T> | undefined;
    getEntities: (filter?: (entity) => boolean) => ParsedEntity<T>[];
    getEntitiesByModel: (namespace: keyof T, model: keyof T[keyof T]) => ParsedEntity<T>[];
    getHistoricalEntities: (entityId: string) => ParsedEntity<T>[];

    // Subscriptions
    subscribeToEntity: (entityId: string, listener: (entity) => void) => () => void;
    waitForEntityChange: (entityId: string, predicate: (entity) => boolean, timeout?: number) => Promise<ParsedEntity<T> | undefined>;

    // Cleanup
    resetStore: () => void;
}

Accessing Store Data

import { useDojoSDK } from "@dojoengine/​sdk/​react";

function GameComponent() {
    const { useDojoStore } = useDojoSDK();

    // Get single entity
    const player = useDojoStore(state => state.getEntity(entityId));

    // Get all entities with filter
    const activePlayers = useDojoStore(state =>
        state.getEntities(e => e.models?.game?.Player?.isActive)
    );

    // Get entities by model
    const allPlayers = useDojoStore(state =>
        state.getEntitiesByModel("game", "Player")
    );
}

Optimistic Updates

Optimistic updates show changes immediately while the transaction confirms:

function movePlayer(direction: string) {
    const { useDojoStore, provider } = useDojoSDK();
    const store = useDojoStore.getState();

    const transactionId = `move-${Date.now()}`;

    // 1. Apply optimistic update immediately
    store.applyOptimisticUpdate(transactionId, (draft) => {
        const entity = draft.entities[entityId];
        if (entity?.models?.game?.Position) {
            entity.models.game.Position.x += direction === "right" ? 1 : -1;
        }
    });

    try {
        // 2. Execute the actual transaction
        await provider.execute(account, {
            contractName: "actions",
            entrypoint: "move",
            calldata: [direction]
        }, "game");

        // 3. Confirm on success (removes pending state)
        store.confirmTransaction(transactionId);
    } catch (error) {
        // 4. Revert on failure
        store.revertOptimisticUpdate(transactionId);
    }
}

Entity Subscriptions

function useEntitySubscription(entityId: string) {
    const { useDojoStore } = useDojoSDK();
    const store = useDojoStore.getState();

    useEffect(() => {
        const unsubscribe = store.subscribeToEntity(entityId, (entity) => {
            console.log("Entity changed:", entity);
        });

        return () => unsubscribe();
    }, [entityId]);
}

Waiting for Entity Changes

async function waitForMove(entityId: string) {
    const { useDojoStore } = useDojoSDK();
    const store = useDojoStore.getState();

    const entity = await store.waitForEntityChange(
        entityId,
        (entity) => entity?.models?.game?.Position?.x > 10,
        30000 // 30 second timeout
    );

    if (entity) {
        console.log("Player reached position:", entity.models.game.Position);
    }
}

Historical Entities

function PlayerTimeline({ entityId }) {
    const { useDojoStore } = useDojoSDK();

    const history = useDojoStore(state =>
        state.getHistoricalEntities(entityId)
    );

    return (
        <ul>
            {history.map((snapshot, i) => (
                <li key={i}>
                    Position: ({snapshot.models.game.Position.x}, {snapshot.models.game.Position.y})
                </​li>
            ))}
        </​ul>
    );
}

Merging Entities from Subscriptions

const { sdk, useDojoStore } = useDojoSDK();

await sdk.subscribeEntityQuery({
    query: query,
    callback: ({ data }) => {
        if (data) {
            // Merge updates into store
            useDojoStore.getState().mergeEntities([data]);
        }
    }
});

Common Pitfalls

  1. Forgetting to confirm/​revert: Always handle both success and error cases for optimistic updates
  2. Stale closures: Use useDojoStore.getState() for callbacks to avoid stale state
  3. Over-subscribing: Use selectors to minimize re-renders
  4. Missing cleanup: Always unsubscribe from entity subscriptions on unmount

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View