Check out a free preview of the full State Machines in JavaScript with XState, v2 course

The "History States Exercise" 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:

Students are instructed to go to the most recent child of the 'ready' state by adding a sibling history state.

Preview
Close

Transcript from the "History States Exercise" Lesson

[00:00:00]
>> Let's go to our next exercise, which is on history states. Currently, there is a problem with our application. Not sure if you notice, but right now in our application, if we press next, and then we load the song. Everything seems to be working. Now let's say right now this player is currently in the playing states, or really it's in the ready playing state.

[00:00:29]
Let's say that we pause this. And now let's say that we skip to the next song. So now we're loading and we loaded the song. Now the next song is going to immediately start playing. This can be undesired behavior because previously, we pause the song, and then we skipped.

[00:00:50]
So what a user would expect to happen would be that the player should still be in the paused state, because that's what we were previously on. And we pause the song for a reason. So, what we're going to do is we're going to model this in the state chart, right now, when the loaded event happens, we go directly to the ready states and the ready state.

[00:01:12]
The initial state is always playing right now, but what we want to do is instead we want to visit the most recently active state in this ready compound state. So that if we were on the pause state when we revisit this ready State, we want to go back to the paused State instead of going to the playing state by default.

[00:01:35]
So add a sibling history state here. And, yeah, go ahead and implement it, by the way, the way that history states are defined in X state. So, let me. Just go here real quick. Is that when you have a compound state, so if we have initial test, states test, and you would specify the history state by naming it wherever you want.

[00:02:09]
Typically I like to name it hist and then you specify a type of history. And then by default the history seat is going to be a shallow history state but if you want it to be a deep history state, you give it a history value of deep. But this is not a common use case, so typically all you need to do is specify type as history.

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