Check out a free preview of the full State Machines in JavaScript with XState, v2 course:
The "Guards" Lesson is part of the full, State Machines in JavaScript with XState, v2 course featured in this preview video. Here's what you'd learn in this lesson:

David discusses what guarded transitions are, inline guards, serialized guards, multiple guarded transitions, and eventless transitions.

Get Unlimited Access Now

Transcript from the "Guards" Lesson

[00:00:00]
>> The next thing I wanna talk about is guards, or specifically guarded transitions. What are guarded transitions? Typically when we have a transition, the transition tells us which states to potentially go to next based on the events, but sometimes that isn't sufficient. We want to take that transition only if the event of course is the one received, and if we have some sort of condition that is true.

[00:00:30] So this is what is meant by guarded transitions. And just to give you an example over here we're gonna go back into our main state machine that we have here. All right, so let's say that we have a SKIP event over here, just in our contrived state machine.

[00:00:51] And I want this to go to the loaded state, which is over here, so target loaded. But I only want it to go to the loaded state if some condition is met. So I'm gonna say cond for condition, and we're just gonna be doing this inline. We want this transition to only be taken if the context.count is greater than 100, for instance.

[00:01:18] All right, so if I go to the machine, and we see that we have the context over here, so I'm going to also log the state.value. So you see we're in the loading state and the count is 42. So if I send a SKIP event, then you're going to see that it's still going to stay in the same loading state.

[00:01:46] And that's because the count is not greater than 100. So now let's change that. Let's say that the count either originally is greater than 100 or another event caused the assign action that we learned in the previous module to change the counts to something above 100, so 101.

[00:02:03] Now when we send the exact same event, that transition will be taken, and we will get to the loaded state. So assigning guards to transitions can be done inline like this, or just like actions you could specify it as a string too. So we could say greater than 100.

[00:02:26] And then we could add a configuration option here under guards and say greater than 100 and provide that in right there. So now, again, when we try the same event, it's going to take us to the loaded state. So those are the two ways of specifying a condition over here.

[00:02:50] Specifying it as a string is better for visualizing, cuz you can see the name directly in the visualizer. But if you're quickly prototyping a state machine, then you could easily just specify that condition inline.