Skip to content

Function: definePlayer()

API / @xmachines/play-xstate / definePlayer

function definePlayer<TMachine>(config): PlayerFactory<TMachine>;

Defined in: packages/play-xstate/src/define-player.ts:61

Creates a player factory from an XState machine

This factory function accepts an XState v5 machine. It returns a function that makes PlayerActor instances. One configuration can therefore make more than one actor instance, and this helps with a test, with an application of several instances, and with a render on the server.

Type Parameters

Type ParameterDescription
TMachine extends AnyStateMachineThe type of the XState v5 state machine

Parameters

ParameterTypeDescription
configPlayerConfig<TMachine>The configuration object of the player

Returns

PlayerFactory<TMachine>

The factory function. It makes an actor instance, with an optional input context

Examples

A basic player factory

import { setup } from "xstate";
import { definePlayer } from "@xmachines/play-xstate";
const machine = setup({}).createMachine({
initial: "idle",
states: {
idle: { meta: { route: "/" } },
active: { meta: { route: "/active" } },
},
});
const createPlayer = definePlayer({ machine });
const actor = createPlayer();
actor.start();

More than one actor instance from one factory

const createPlayer = definePlayer({ machine });
// Create an actor for each user
const alice = createPlayer({ userId: "alice" });
const bob = createPlayer({ userId: "bob" });
alice.start();
bob.start();
// The two state machines are independent
console.log(alice.state.get() !== bob.state.get());

See