Skip to Content
DocsGame ServerGlobal State

Managing Global State

This guide explains how to manage global state in Agent8. Use global state to store and update game-wide configurations—such as game status, maintenance messages, and other settings—that affect all users.

Understanding Global State

Global state in Agent8 is shared among users and can be accessed using the functions $global.getGlobalState() and $global.updateGlobalState(). Because the state persists between requests, it is ideal for managing configurations and statuses that apply to the entire application.

Remember: Global state is shared by all users, so it is best used for announcements, system status updates, and other settings that need to be consistent.

Server API

  • $global.getGlobalState(): Promise<Object>: Retrieves the current global state.
  • $global.updateGlobalState(state: Object): Promise<Object>: Updates the global state with new values.
server.js
class Server { async getGlobalState() { return await $global.getGlobalState(); } async updateGlobalState(state) { return await $global.updateGlobalState(state); } }

Merge Semantics Example

When updating global state, new values are merged with existing ones:

server.js
class Server { async demonstrateMerge() { const state = await $global.getGlobalState(); // e.g., { "name": "kim" } await $global.updateGlobalState({ age: 18 }); const newState = await $global.getGlobalState(); // { "name": "kim", "age": 18 } return newState; } }

Client API

subscriptions

  • server.subscribeGlobalState((state: any) => {}): UnsubscribeFunction

hooks

  • const globalState = useGlobalState()

Subscribe to Global State Updates

// Example using the useGameServer hook: import { useGameServer } from "@agent8/gameserver"; import { useEffect } from "react"; function GlobalStateComponent() { const { connected, server } = useGameServer(); useEffect(() => { if (!connected) return; const unsubscribe = server.subscribeGlobalState((state) => { // Handle state updates here console.log("Global state updated:", state); }); // Cleanup subscription when component unmounts return () => unsubscribe(); }, [connected, server]); return <div>Global State Component</div>; }

Sync Global State with React Hooks

For real-time global state synchronization in React components:

import { useGlobalState } from "@agent8/gameserver"; function GlobalStateDisplay() { const globalState = useGlobalState(); return ( <div> <h2>Global State</h2> <pre>{JSON.stringify(globalState, null, 2)}</pre> </div> ); }

The useGlobalState hook automatically handles subscriptions and unsubscriptions, making it the recommended approach for React applications.


Example 1: Global Counter

This example demonstrates a persistent counter that increments across all clients. The server manages the counter, while the clients display and update it in real-time.

server.js
class Server { async countup() { const currentState = await $global.getGlobalState(); const newCount = (currentState.count || 0) + 1; await $global.updateGlobalState({ count: newCount }); return { count: newCount }; } }
src/App.tsx
import { useGameServer, useGlobalState } from "@agent8/gameserver"; export default function CountUp() { const { connected, server } = useGameServer(); const globalState = useGlobalState(); if (!connected) return <p>Loading...</p>; return ( <div> <p>Count: {globalState.count || 0}</p> <button onClick={() => server.remoteFunction("countup")}> Increase Count </button> </div> ); }

Example 2: Maintenance Mode

This example implements a maintenance mode toggle with admin authentication. Only administrators can activate or deactivate maintenance mode, and the change is broadcast to all connected clients.

server.js
class Server { isAdmin() { const ADMIN_ACCOUNT = "0x1234567890123456789012345678901234567890"; // Using $sender.account to get the current user's account return $sender.account === ADMIN_ACCOUNT; } async setMaintenanceMode(enabled, message) { if (!this.isAdmin()) { return { error: "Unauthorized action" }; } await $global.updateGlobalState({ status: enabled ? "MAINTENANCE" : "ACTIVE", maintenanceMessage: enabled ? message : null, lastUpdated: Date.now(), }); return $global.getGlobalState(); } }
src/App.tsx
import { useGameServer, useGlobalState } from "@agent8/gameserver"; export default function MaintenanceToggle() { const { connected, server } = useGameServer(); const globalState = useGlobalState(); if (!connected) return <p>Loading...</p>; const handleToggle = async () => { const enable = globalState.status === "ACTIVE"; const newMessage = enable ? prompt( "Enter maintenance message:", globalState.maintenanceMessage || "" ) : null; await server.remoteFunction("setMaintenanceMode", [enable, newMessage]); }; return ( <div> <p>Status: {globalState.status || "ACTIVE"}</p> {globalState.status === "MAINTENANCE" && ( <p> Message:{" "} {globalState.maintenanceMessage || "Maintenance mode activated"} </p> )} <button onClick={handleToggle}> {globalState.status === "ACTIVE" ? "Enable Maintenance Mode" : "Disable Maintenance Mode"} </button> </div> ); }
Last updated on