In-state guards
You can check if the machine is in a certain state using an in
property on a transition. The in
property takes a state ID as an argument and returns true
if that state node is active in the current state, which can be useful in parallel states.
In the example below, when the machine receives the LOG_WHEN_ACTIVE
event, we check if the machine is in the active
state, specified by id, then logIsActive
.
import { createMachine } from 'xstate';
const lightMachine = createMachine(
{
type: 'parallel',
states: {
toggle: {
initial: 'inactive',
states: {
inactive: {
on: {
TOGGLE: 'active',
},
},
active: {
id: 'active',
on: {
TOGGLE: 'inactive',
},
},
},
},
logger: {
on: {
LOG_WHEN_ACTIVE: {
in: '#active',
actions: 'logIsActive',
},
},
},
},
},
{
actions: {
logIsActive: () => {
console.log('Active!');
},
},
},
);
Combining cond
and in
​
You can combine a cond
with an in
property. Both the cond
and the in
will need to resolve to true
for the machine to transition.