createMachine
createMachine<
SF
,TC
,FC
,E
>(states
:SF
,transitions
:TC
,init
:KeysWithZeroRequiredArgs
<FC
["states"
]> |FactoryKeyedState
<FC
["states"
]>):FactoryMachine
<FC
>
Defined in: factory-machine.ts:59
Creates a type-safe state machine from a state factory and transitions. Usage:
// Define states and create a machineconst states = defineStates({...})const machine = createMachine(states, transition, initialState)// Setup machine with effects, guards, etc.setup(machine)(effect(...), guard(...))// Use the machinemachine.send("eventName", ...params)machine.getState().match({ StateKey: (data) => { ... }, AnotherStateKey: (data) => { ... }, // ...})
Type benefits:
- Transition types and event parameters are inferred from state factory
- State and event keys are autocompleted
- Pattern matching and type guards for states and events
- Exhaustive match on state and event keys
- API for sending events, inspecting state, and matching on state
Type Parameters
Section titled “Type Parameters”Type Parameter | Default type |
---|---|
SF extends KeyedStateFactory | - |
TC extends FactoryMachineTransitions <SF > | - |
FC extends FactoryMachineContext <SF > | { states : SF ; transitions : TC ; } |
E extends TransitionEvent <ReturnType <FC ["states" ][keyof FC ["states" ]]>, ReturnType <FC ["states" ][keyof FC ["states" ]]>> & FactoryMachineEventApi <FC > & { from : ReturnType <FC ["states" ][keyof FC ["transitions" ] extends keyof FC ["states" ] ? keyof FC ["states" ] & keyof FC ["transitions" ] : any ]>; type : keyof FC ["transitions" ][keyof FC ["transitions" ]]; } | FactoryMachineEvent <FC > |
Parameters
Section titled “Parameters”Parameter | Type |
---|---|
states | SF |
transitions | TC |
init | KeysWithZeroRequiredArgs <FC ["states" ]> | FactoryKeyedState <FC ["states" ]> |
Returns
Section titled “Returns”FactoryMachine
<FC
>
Example
Section titled “Example” const machine = createMachine( states, { Idle: { search: "Loading" }, Loading: { success: (results: string[]) => (ev) => states.Success(ev.from.data.query, results), error: (message: string) => (ev) => states.Error(ev.from.data.query, message), }, Success: {}, Error: {}, }, "Idle" ); machine.send("search", "query") machine.getState().key // "Loading" machine.getState().match({ Idle: () => ..., Loading: ({ query }) => ..., Success: ({ results }) => ..., Error: ({ message }) => ... })