Always
Sometimes you’ll need to make checks in your statechart’s current state without receiving an event. You can do this with an eventless transition.
Eventless transitions are transitions without events. These transitions are always taken after any transition in their state if enabled. Eventless transitions are labeled “always” and often referred to as “always” transitions.
A simple example is a state that always transitions from a
to b
:
import { createMachine } from 'xstate';
const machine = createMachine({
initial: 'a',
states: {
a: {
always: [
{
target: 'b',
},
],
},
b: {},
},
});
Using the always
transition means that a
will instantly transition to b
when the machine enters the a
state.
Adding guards​
You can also pair always
transitions with a guard:
import { createMachine } from 'xstate';
const machine = createMachine(
{
initial: 'a',
states: {
a: {
always: [
{
cond: 'shouldTransition',
target: 'b',
},
],
},
b: {},
},
},
{
guards: {
shouldTransition: (ctx) => ctx.user.role === 'admin',
},
},
);
In the example above, the transition will only happen when shouldTransition
returns true. Otherwise, the machine will stay in the same state.
“Always” transitions are checked immediately when the machine enters the state node, after checking for regular transitions and before checking if there are any transitions for any other queued events.