Communicate between State Machines in Different Components

Isaac Mann
InstructorIsaac Mann
Share this video with your friends

Social Share Links

Send Tweet

All of this code lives in one component so far, but our apps have multiple components. We'll split the app into list components and a question component with each component having its own state machine. Each component will update its own state machine when it receives an event from a different component.

Instructor: [00:00] This app component is using two different machines, the matching machine and the fetch machine. Also, the fetch machine is used twice, once for people and once for planets. Let's create a list component that will use the fetch machine and handle rendering a list.

[00:15] We'll just copy everything in the app component, make a new list.tsx file, paste in the app component content and then delete what we don't need. Change our references to app to list. Fetch people and fetch planets will be passed to us from the parent component and remove all references to the matching machine.

[00:36] We'll rename fetch people state to fetch data state and send to people machine should become send to data machine. Let's add a prop here for fetch data and use that here. We don't need the planet state, we can remove that. Scroll down. We'll come back to fix the matching state references.

[01:05] Now we just need to fix these references to the matching machine. We'll have the parent component pass in the selected item and we'll use an on selection prop pass back the item that was selected. Here let's rename person to item.

[01:21] Now we needed to find these props, selected item, on selection. Fetch data is a function that returns a promise with results that's an array. Selected item could be anything. On selection takes any item and returns void.

[01:50] Let's clean up the styles on this button to use a class instead. If it's selected, it should have the selected class and it should always have a class of list button. Let's update the app component. Don't need the fetch machine anymore. We'll use the list component here and import it.

[02:21] Fetch data for this one is fetch people. Selected item is matching state.context.topSelectedItem. On selection, we'll take the selected item and send to the match machine. Select top event with the selected item.

[02:48] Do the same thing for planets. Fetch planets, bottom selected item, and select bottom. Now, let's see if that worked. Just like before, we can select the top and the bottom or the bottom and then the top.

[03:09] With this free factor, it's clear that the matching machine knows nothing about the fetch machine. They simply coordinate their actions by sending messages through components props.