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

The "Parallel 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 parallel states exercise.


Transcript from the "Parallel States Solution" Lesson

>> All right, let's talk about adding parallel states into our application. Again, we want it to look like this where we have player and volume. All right, so the first thing to do is to actually have those two states as the child states of this machine, which this machine itself is going to be the parallel state.

So we have to first specify type parallel and then our states. And I know things are being duplicated right now, but that's what happens while you're refactoring. So our states are going to be ready, or sorry, not ready. Our states are going to be player and volume. And so now we can move all of these states over here, well, not all of them.

But we can move this initial into there and then we're going to be copying the loading and ready states over here into states. So let's just close that up and now we're gonna be copying these two states into volume. The initial state is going to be unmuted, and so now we have our states of unmuted and muted.

Now we have an extra thing over there. All right, so now let's test our application and see what we have, six parallel states. Okay, so if everything works, now we should have a volume that mutes and unmutes. So we know that that region is working, and so we also have our play and pause working as well.

So we know that these are working. Now if you want to do something extra, you could also scope these events to their appropriate reasons. For example, the skip, like, unlike, dislike, and audio.time, these are transitions that only have actions, except for this target one which is targeting an ID so we can move it anywhere anyway.

We can move those to here. And so now we have everything nice and organized inside of this player state. And we could see, okay, the player region is responsible for these skip, like, unlike, dislike, and audio.time events. And so, we could do the same thing over here for the volume controls and just put it on there.

And so, now we don't need this anymore and everything should be working the same.

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