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

The "State Modeling 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 create a state machine transition function for the loading play and pause function of the media player using a switch statement or an object. Then determine a simple way to interpret it and make it an object that accepts .send events.


Transcript from the "State Modeling Exercise" Lesson

>> We're going to be jumping into the first exercise. And so, if you go to localhost, port 3000, /00-modeling, you could also access this by clicking the link over here. You're going to see a media player, and this doesn't exactly need to be hooked up just yet. It just serves as a visual guide for now.

What we're gonna be mainly doing is working in the console itself. And so, for this exercise, what I want you to do is, you're gonna see a main.js file. We're going to be creating a simple state machine that represents the loading, play, and pause functionality of our media player.

And so, let's first create the state machine visually over here. So instead of loading, or sorry, instead of idle, our initial state is going to be loading. And this represents loading the song, we're going to have a loaded event. And so, according to the specification, when the song is loaded, we're gonna start playing it.

So the state machine goes to the playing state. Now, we could go back and forth between the playing and paused states using events. So we could go from playing to paused when we pause it. And we could go from paused to playing, When the play event happens. So basically, I want you to represent this state machine in code without using any libraries.

And yeah, so you could use either a switch statement or an object. And just like we did by attaching the transition function to the window, play around with it, look in the console. Make sure that all of the transitions are actually working. And then if you want to, find a way to localize that state, so you have this object that you could just send events to.

If you don't get that far, then that's okay, we're gonna be doing it together, cuz that's gonna be an important concepts later on.

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