Skip to main content

MachineState

The object returned from injectMachineStore()'s createState factory. The MachineState's API is used to define the state machine's transitions, listeners, and guards.

Creation

const machineStore = injectMachineStore(createState => {
const onState = createState('on')
const offState = createState('off')

return [onState.on('toggle', 'off'), offState.on('toggle', 'on')]
})

Definition

interface MachineState<
Context extends Record<string, any> | undefined = any,
Name extends string = string,
Events extends string[] = [],
ChildStates extends string[] = []
> {
on: <E extends string, S extends string>(
eventName: E,
nextState: S,
guard?: (context: Context) => boolean
) => MachineState<Context, Name, [...Events, E], [...ChildStates, S]>
onEnter: (
listener: MachineHook<ArrToUnion<ChildStates>, ArrToUnion<Events>, Context>
) => MachineState<Context, Name, Events, ChildStates>
onLeave: (
listener: MachineHook<ArrToUnion<ChildStates>, ArrToUnion<Events>, Context>
) => MachineState<Context, Name, Events, ChildStates>
stateName: Name
}
on

Defines a transition for the machine from the current state to another state in the machine.

Can be given a guard function to conditionally prevent the transition from occurring.

Signature:

on = (eventName, nextState, guard?) => machineState
eventName

Required. A string. Represents an event name that will be sent to the machine store via machineStore.send(eventName).

nextState

Required. A string. Will usually exactly match another MachineState's stateName.

guard

Optional. A function that's called every time the machine is about to take this transition. Receives the machine store's current .context value and must return true to allow the transition.

Returns

The MachineState for chaining.

onEnter

Registers an enter listener with the machine store. This listener will be called every time the machine enters this state (after entering it).

The listener's signature is:

(store, storeEffect) => void

It receives a reference to the machine store and the StoreEffect object that triggered the state change.

onLeave

Registers a leave listener with the machine store. This listener will be called every time the machine exits this state (after transitioning to the next state).

The listener's signature is:

(store, storeEffect) => void

It receives a reference to the machine store and the StoreEffect object that triggered the state change.

stateName

A string. Will be set to the string passed to injectMachineStore()'s createState() factory.

injectMachineStore(state => {
const stateA = state('a')
stateA.stateName === 'a' // true
...
})

See Also