Actions
Enqueue effects during a transition.
XState v6 is in alpha
Use the enqueue argument from a transition, entry or exit function.
entry: ({ context }, enq) => {
enq(() => console.log('Entered', context));
}Entry and exit functions also receive stateNode, the state node being entered or exited, and input, the state's input. Transition functions do not receive stateNode.
entry: ({ stateNode }, enq) => {
enq(() => console.log('Entered', stateNode.id));
}Built-in actions
| Method | Purpose |
|---|---|
enq(...) | Enqueue an effect function. |
enq.raise(...) | Send an event to the same actor. |
enq.sendTo(...) | Send an event to an actor ref or a statically declared child id. |
enq.spawn(...) | Spawn a child from actor logic or its typed registered name. |
enq.stop(...) | Stop an actor. |
enq.cancel(...) | Cancel a delayed event. |
enq.log(...) | Log values. |
enq.emit(...) | Emit an actor event. |
enq.listen(...) | Map another actor's emitted events to events for this machine. |
enq.subscribeTo(...) | Map another actor's snapshots and outcomes to events for this machine. |
Provide reusable named action sources through setup(...).
enq.sendTo(...) to a missing target (an undefined ref, a child id with no running child, or parent in a root actor) does not error the sender. The event becomes a dead letter with reason 'missingTarget': the root actor's onRejectedEvent option receives it (with reason, targetId and sourceRef) and development builds log a warning that names the sender and the target.
Actions are fire-and-forget. XState does not wait for a promise returned by an action. Use invoked async logic when the result changes what happens next.
Use actions for work such as:
- recording analytics after an order is submitted
- focusing a field when a form enters an invalid state
- notifying another actor that a job is ready
TypeScript
Action arguments are inferred from context and event schemas. A child declared
in schemas.children can be addressed by id; its actor-ref schema determines
which events are accepted.
Actions cheatsheet
entry: (_, enq) => enq(() => startEffect())
exit: (_, enq) => enq(() => stopEffect())
on: {
ping: (_, enq) => {
enq.sendTo('worker', { type: 'ping' });
}
}