fn

createAsyncMachine

tested

Create a type-safe async finite state machine with context

Example

ts
const machine = createAsyncMachine({
  initial: 'idle',
  context: { data: '' },
  states: {
    idle: {
      on: {
        FETCH: {
          target: 'loaded',
          guard: async () => await hasPermission(),
          action: async (ctx) => { ctx.data = await fetchData(); },
        },
      },
    },
    loaded: {
      entry: async (ctx) => { await saveToCache(ctx.data); },
    },
  },
});

await machine.send('FETCH'); // 'loaded'

Signatures

ts
export function createAsyncMachine<
  const States extends Record<string, AsyncStateNodeConfig<Context>>,
  Context,
>(config: {
  initial: NoInfer<ExtractStates<States>>;
  context: Context;
  states: States;
}): AsyncStateMachine<ExtractStates<States>, ExtractEvents<States>, Context>;
ts
export function createAsyncMachine<
  const States extends Record<string, AsyncStateNodeConfig<undefined>>,
>(config: {
  initial: NoInfer<ExtractStates<States>>;
  states: States;
}): AsyncStateMachine<ExtractStates<States>, ExtractEvents<States>, undefined>;

Parameters

ParameterTypeDescription
config{ initial: string; context?: unknown; // Overload-implementation signature: the typed overloads above expose the real // per-context API; `any` here accepts every concrete `AsyncStateNodeConfig<C>` // (contravariant in `C`, so `unknown` would reject them). states: Record<string, AsyncStateNodeConfig<any>>; }

Returns

AsyncStateMachine
PropertyTypeDescription
send(event: string) => Promise<string>Send an event to the machine, awaiting async guards, actions, and hooks
can(event: string) => Promise<boolean>Check if an event can trigger a transition, awaiting async guards
currentStateStates
statesRecord<string, NodeConfig>
contextContextMachine context
currentstringCurrent state of the machine
matches(state: string) => booleanCheck if the machine is in a specific state