V5 beta - Starting a finite state machine in an arbitrary state #4318
-
I particularly like the idea of using state machines in a UI library. It would be especially nice to be able to separate a component's logic from a given framework. One thing I'm struggling with is how would you go about starting a machine in an arbitrary finite state? I reviewed the documents (https://stately.ai/docs/xstate-v5/persistence), and it generally seems like there are two approaches:
This makes sense for complex states or states that are not finite (i.e. states with additional context), but what about if the state is relatively simple? I.e. given this example: import { createMachine } from "xstate";
export const machine = createMachine(
{
id: "Parallel Toggle",
states: {
Mutability: {
description: "Is the toggle's position modifiable?",
initial: "Mutable",
states: {
Immutable: {
on: {
TOGGLE_MUTABILITY: {
target: "Mutable",
},
},
},
Mutable: {
on: {
TOGGLE_MUTABILITY: {
target: "Immutable",
},
},
},
},
},
Position: {
description: "The position that the toggle is currently in",
initial: "On",
states: {
On: {
on: {
TOGGLE_POSITION: {
target: "Off",
guard: stateIn({ Mutability: "Mutable" }),
},
},
},
Off: {
on: {
TOGGLE_POSITION: {
target: "On",
guard: stateIn({ Mutability: "Mutable" }),
},
},
},
},
},
},
type: "parallel",
types: {
events: {} as
| { type: "TOGGLE_MUTABILITY" }
| { type: "TOGGLE_POSITION" },
},
},
{
actions: {},
actors: {},
guards: {},
delays: {},
},
); I may want to initialize the component in an immutable state or in the off position (or vice versa). I assume that this is the method that you would use: import { machine } from '$lib/machines/toggle';
import { createActor } from 'xstate';
let actor = createActor(machine, {
state: machine.resolveStateValue({ Mutability: 'Immutable', Position: 'Off' })
});
actor.start(); Is this the correct approach? Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Yes, using However, this function does not give a way for you to provide There is a PR that provides a helpful error if you pass in an incompatible state value: #4290 |
Beta Was this translation helpful? Give feedback.
Yes, using
machine.resolveStateValue(...)
is the correct approach if you're just providing a state value.However, this function does not give a way for you to provide
context
if you need that, so just be aware of that.There is a PR that provides a helpful error if you pass in an incompatible state value: #4290