State Modeling in React with XState

Guarded Transitions Exercise

State Modeling in React with XState

Check out a free preview of the full State Modeling in React with XState course

The "Guarded Transitions Exercise" Lesson is part of the full, State Modeling in React with XState course featured in this preview video. Here's what you'd learn in this lesson:

Students are instructed to use guarded transitions to model what happens when the timer expires.


Transcript from the "Guarded Transitions Exercise" Lesson

>> Okay, so let's get to exercise 4, which is on guarded transitions. This exercise is basically to fix the logic that we have here. I put the timer at the 5 seconds to make it easier to test, but right now when you click the timer, it goes to 5, 4, 3, 2, 1.

And then it just sort of keeps going. So what we want to do, is we want to use guarded transitions to basically make sure that doesn't happen. So, the first goal whenever a tic event happens, we only want to increments the context, that elapsed when incrementing it won't exceed the context duration.

So, you're going to have a guard that says, does context duration plus context dot interval, this context that elapsed plus context dot interval exceed the duration. If so, we wants to go to in expired states. Otherwise, we wanna just keep doing the same thing we were doing before.

And then like we just talked about, you can also parameterize that cond and optionally put it in the guards. And so in the expired state, we also want to reset events to transition back to idle.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now