createMachine()
createMachine<
S,E>(definition,initial):object
createMachine<
S,E,C>(definition,initial,initialContext):object
Creates a finite state machine.
Type Parameters
S: S extends string
Union of state names
E: E extends string
Union of event names
C: C
Context type
Parameters
Overload 1:
definition: MachineDefinition<S, E, undefined>
The state/transition map
initial: S
The initial state
Overload 2:
definition: MachineDefinition<S, E, C>
The state/transition map
initial: S
The initial state
initialContext: C
The initial context value
Returns: object
A machine with current, send, matches, trySend, onTransition, reset
current(): () => S
Returns: S
send(): (event) => S
event:
E
Returns:S
matches(): (state) => boolean
state:
S
Returns:boolean
trySend(): (event) => Option<S>
event:
E
Returns:Option<S>
onTransition(): (listener) => () => void
listener:
TransitionListener<S, E>
Returns:> (): void
Returns: void
reset(): () => void
Returns: void
Since
2.4.0
Example
const door = createMachine({
locked: { unlock: { to: "closed" } },
closed: { open: { to: "opened" }, lock: { to: "locked" } },
opened: { close: { to: "closed" } },
}, "locked");
door.send("unlock"); // "closed"
door.send("open"); // "opened"
door.matches("opened"); // true
SimpleTransition<S>
A simple transition to a target state.
Since
2.4.0
Type Parameters
S: S extends string
Union of state names
Properties
to
readonlyto:S
ContextTransition<S, C>
A transition that updates context.
Since
2.4.0
Type Parameters
S: S extends string
Union of state names
C: C
Context type
Properties
to: S
update(): (ctx) => C
ctx:
C
Returns:C
Transition<S, C>
Transition<
S,C> = SimpleTransition<S> | ContextTransition<S,C>
A transition is either simple (just target) or with context update.
Type Parameters
S: S extends string
Union of state names
C: C
Context type
Since
2.4.0
Transitions<S, E, C>
Transitions<
S,E,C> ={ readonly [K in E]?: Transition<S, C> }
A transition map for a single state.
Type Parameters
S: S extends string
Union of state names
E: E extends string
Union of event names
C: C
Context type
Since
2.4.0
MachineDefinition<S, E, C>
MachineDefinition<
S,E,C> ={ readonly [K in S]: Transitions<S, E, C> }
Full state machine definition.
Type Parameters
S: S extends string
Union of state names
E: E extends string
Union of event names
C: C
Context type
Since
2.4.0
TransitionListener()<S, E>
TransitionListener<
S,E> = (from,event,to) =>void
A transition listener receives the previous state, the event, and the new state.
Type Parameters
S: S extends string
Union of state names
E: E extends string
Union of event names
Parameters
from: S
event: E
to: S
Returns: void
Since
2.4.0