Skip to content

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 machine
const states = defineStates({...})
const machine = createMachine(states, transition, initialState)
// Setup machine with effects, guards, etc.
setup(machine)(effect(...), guard(...))
// Use the machine
machine.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 ParameterDefault 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>
ParameterType
statesSF
transitionsTC
initKeysWithZeroRequiredArgs<FC["states"]> | FactoryKeyedState<FC["states"]>

FactoryMachine<FC>

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 }) => ...
})