Check out a free preview of the full State Machines in JavaScript with XState, v2 course
The "Final States Solution" 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 walks through the solution to the final states exercise.
Transcript from the "Final States Solution" Lesson
[00:00:00]
>> All right, so let's add final states into our application just to clean things up a little bit, since we are targeting this loading state with an ID, and we want to avoid doing that just to model things a little bit more cleanly. So first things first, instead of going to loading, let's make a finished state right over here, and let's target that state instead.
[00:00:26]
So what's happening over here is when the elapsed is greater than the duration, now we're saying okay, this song is now gonna be finished. And by doing that we are now just separating from the fact that we have this loading state. So now we don't even need to know about this loading state because it becomes the responsibility of the player states.
[00:00:49]
So if we want to change this loading state and maybe just, we have a song already cached or we want to replay the song if we're on repeat and we don't need to load it again. Then none of those details matter because all we're saying is, hey, parent state, I'm finished.
[00:01:07]
And so we specify that with type: [COUGH] 'final'. All right, so now we are going to make sure that everything still works. And we're going to go to 07-final-states. [COUGH] So now we see that play and pause still work. But we do want to trigger this when elapsed is greater than or equal to duration.
[00:01:38]
And again, the way that this happens is using the AUDIO.TIME event. So, if we do service.send, type: 'AUDIO.TIME', and we give it a currentTime of something big, like 1,000. What should happen is it should go back to the loading state, which it does. And of course we could go from loading to loaded.
[00:02:06]
I'm just gonna copy this, and see that it goes back there. So our final state is working.
Learn Straight from the Experts Who Shape the Modern Web
- In-depth Courses
- Industry Leading Experts
- Learning Paths
- Live Interactive Workshops