Send Events to the Machine with the XState Send Action Creator

Kyle Shevlin
InstructorKyle Shevlin
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

XState provides the send function to create an action that will send the event passed in to the machine. If we provide the second argument to the send function, the options object, we can send the event to a particular machine. This is useful when you have invoked a machine as a service on a state node, a concept that will be explored in a later lesson.

Instructor: [0:00] Here I have an echo machine with one state, listening, and two events, speak and echo. What I'd like this machine to do is any time I speak, I want the echo event to be triggered. How can I do this? I can use a special action called the send action creator to send events to my machine.

[0:20] I'm going to add the actions property here. Then I'm going to use the send function. The send function receives an event. In this case, it'll be echo. We update our machine. We now see that speak is an available event to send. When we send the speak event, it'll send an echo event on the next tick of the machine.

[0:40] I'm going to open up the console. Reset the machine. We'll call speak. Every time we do, it echoes out. We can also update this from being just a string to an object with a type of event that we want to send. This too will also send echoes.

egghead
egghead
~ 2 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today