Handle React Events as Streams with RxJS and Recompose

John Lindquist
InstructorJohn Lindquist

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 4 years ago

Events are the beginning of most every stream. Recompose provides a createEventHandler function to help your create handler and stream pairs. Once the handler/stream pairs are created, it’s simply a matter of passing the handlers down the stream as props and combining the streams any way you want.

Instructor: [00:00] Currently, this simple form takes some text and an onInput that simply logs out what you type into the input. If I type in hello, you can see hello show up in the console log. We'll create a simple form stream using component from stream.

[00:20] We'll write some logic inside this block. I want to create a stream off of this onInput to push the changes into text. I can do that with importing createEventHandler. Then I will use createEventHandler, which gives me back an object with a stream and a handler.

[00:46] I'm going to rename these to onInput, a dollar sign to say it's a stream, and onInput, which'll be the function I pass into the component. I'm going to use the onInput stream, get the event off of it, and the event target.value. This can be a text stream.

[01:06] I can return this text stream and map it to some props. I'll say text, and map that to an object which is our props now. That will be the text we want and the onInput handler we defined above. Then we can map that to the simple form.

[01:28] I'll go ahead and use the simple form stream, hit save there, and you'll see that nothing shows up. The only thing that shows up right now is our simple form. Let's go ahead and delete that real quick to show that truly nothing shows up.

[01:45] The reason here is that our text has not triggered yet, because it won't trigger until something comes in on onInput. It's like we didn't define any default props. We can say start with an empty string, and that will trigger our onInput, and push some empty text into here.

[02:06] When I save now, you can see now, a form showed up, and I can stream values in. Then just to make this a little more visually appealing, because we have a stream, and we can do whatever we want with it, I'll add in a delay. I'll say, "Streams are awesome."