This course has been updated! We now recommend you take the State Machines in JavaScript with XState, v2 course.

Check out a free preview of the full State Machines in JavaScript with XState course:
The "Create a State Machine Exercise" Lesson is part of the full, State Machines in JavaScript with XState course featured in this preview video. Here's what you'd learn in this lesson:

Students are instructed to create a state machine first using a switch statement, then using objects, and toggle between the inactive and active state in both implementations.

Get Unlimited Access Now

Transcript from the "Create a State Machine Exercise" Lesson

[00:00:00]
>> Let's go to our first exercise. Hopefully, you have the repo up and running. If you don't, please tell me in the chat and I will try to help you out as much as possible. In the first exercise, where if you run NPM start you will see that.

[00:00:16] And remember, you could just save any file to make the errors disappear. You're gonna see a readme.md. And we're gonna have goals here. And the goal is that we wanna create a state machine that toggles this box elements with an ID of box between the inactive and the active states.

[00:00:37] And so here's the HTML for this exercise. We have a box element here. And this box elements is actually controlled by some CSS where if it has the active state, which I've added for you, then it goes to full opacity. Otherwise, it's just half opacity. So let's take a look at what that looks like.

[00:00:59] So if you navigate to 01 index.HTML, you're gonna see our box over here. Right now it's not inactive or active. So it's just in this faded out blue state, and clicking does nothing. So what I want you to do is I want you to create a very simple state machine first using switch statements and then using objects.

[00:01:24] What you're going to do is, just like we did before, we're going to save the initial state is the inactive state, and we want to toggle between the inactive and active states once we get a click event. And you can name that event whatever you want. So we're going to send the click event, just like we did in the previous example.

[00:01:44] And we are going to set elbox.dataset.state to the current state. What this is going to do, by the way, is it's going to set the data state attributes to whatever that current state is, so for example, inactive. Everything is in the readme. The first thing you want to do is use that switch statement in order to switch between each of the states and then you wanna switch on each of the events.

[00:02:14] And then if you have time, use the object syntax to use an object instead of a switch statement. And that way you can get more of a feel for what XState will feel like.