1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Conditionally Transition to States with Guards in XState

    xstateXState
    >=4.6.7

    Not all transitions should be taken immediately. Occasionally, we would like to conditionally take a transition. We do this through the use of "guards". A "guard" is a predicate function (a function that returns a boolean) that is set on a transition object's cond property (short for "conditional").

    When an event is sent to the machine and it encounters a transition object with a cond property set to a guard function, it will call that function with the current context and event object. If the guard returns true, the transition will be taken, otherwise, it will attempt the next transition for the event, or remain in the current state.

    javascript//...
    EVENT_NAME: {
      target: 'state-name-of-transition-target',
      cond: (context, event) => predicateFunction(context, event)
    }