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

Students are instructed to distribute the state with actors.

Get Unlimited Access Now

Transcript from the "Spawning Actors Exercise" Lesson

>> All right, so let's get started with the final exercise. So if you go to Exercise 8, you're going to be seeing a lot more things. You're gonna see that clock that we showed there and that timer, basically the complete app. But what we want to do is we want to spawn a new timer on the add action.

[00:00:26] So we have this form over here where you could enter, for example, number of seconds such as 31. And pressing play should create a new actor and show that timer over there. Again, if you want to review what this is supposed to look like, you could go to the complete app.

[00:00:48] Press play, we could add a timer, make this 11 seconds, and we can also switch back and forth between these two timers. And so these timers each have their own behavior, and they don't affect one another. So their state is local and private. And so we could also delete these, and then that takes us back here.

[00:01:11] So yeah, play around with the complete app to see how this is supposed to work. But we're going to be invoking that timer machine. So just to show you where things are, if we go to the README [COUGH] in timerAppMachine. Over here is where you're going to be spawning a new timer machine by using the createTimerMachine function.

[00:01:38] By the way, this is a typical pattern that I'd like to use, where if I need a machine whose behavior is only determined at runtime, such as creating a timer with a dynamic duration, then I create a function that creates a machine. And that's simpler than having to just specify machines with context or things like that.

[00:02:07] So that's a pattern I like doing. You could do it a different way, but it's basically going to take that duration and put it right here in the context. So yeah, spawn a new timer machine here, and then we're going to update context.timers to contain that appended spawn timer.

[00:02:27] And also we're going to change context.currentTimer to reflect the index of that spawned timer.