fn
createAsyncMachine
testedCreate 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
| Parameter | Type | Description |
|---|---|---|
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| Property | Type | Description |
|---|---|---|
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 |
currentState | States | — |
states | Record<string, NodeConfig> | — |
context | Context | Machine context |
current | string | Current state of the machine |
matches | (state: string) => boolean | Check if the machine is in a specific state |