Skip to content
Version: XState v4

Guards

guard is a condition that the machine checks when it goes through an event. If the condition is true, the machine follows the transition to the next state. If the condition is false, the machine follows the rest of the conditions to the next state. Any transition can be a guarded transition.

A video player state machine with an initial Paused State and a Playing state. The transition from Playing to Paused has a guard numbered 1 and labeled ‘If time left is zero’. The first guard is joined to a second guard by a dotted line. The second guard is numbered 2 and is labeled ‘Else if time left is more than zero.’ The second guard’s transition targets the Playing state.A video player state machine with an initial Paused State and a Playing state. The transition from Playing to Paused has a guard numbered 1 and labeled ‘If time left is zero’. The first guard is joined to a second guard by a dotted line. The second guard is numbered 2 and is labeled ‘Else if time left is more than zero.’ The second guard’s transition targets the Playing state.

Replace event with a guard

When multiple guard conditions are added to one transition, the guards will be numbered in order. The first guard will be labeled IF and subsequent guards will be labeled ELSE.

On the canvas

  1. Select the event you want to replace with a guarded transition.
  2. Use the plus icon button to open the edit menu.
  3. Choose Guard condition from the menu to add a guarded transition.
  4. Enter your condition into the text input.

Using the transition Details panel

  1. Open the transition Details panel from the right tool menu.
  2. Use the Guard text input to name your guard’s condition and replace your event with a guarded transition.