Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Stream a React Component from an Ajax Request with RxJS

    John LindquistJohn Lindquist

    Loading data using RxJS is simple using Observable.ajax. This lesson shows you how to take the ajax response and pass it along the stream to use as props in a React Component.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: Use this URL to load a person. I'll do this by creating a card stream, which will have an ID of one, which we can pass to that URL. I'll set up my card stream with component from stream. We'll have our props, and then these props will switch map over to an observable.ajax call.

    We'll use our personById function, and pass in the Quick format here, and we want the response off of our response. There's an object called response on there, which is the response body. Then I'll map this over to our card.

    You can see that hitting this URL gave us back an object that had a response. On that response, it had a name of Luke Skywalker and a homeworld of this URL. Let's go ahead and handle that as well. I'm going to extract this and call it loadById. there, and we'll define loadById, that takes an ID and returns that stream that I cut from below. Once we get this response back, I'm going to switch map over to another AJAX call. I'll take this response, say observable.ajax again, and I'm going to say response.homeworld, because we're given the actual URL, as you can see over here on the right.

    Then I want to pluck off the response off this one as well. Switch map has a second argument, which is a result selector. I'll have the out observable and the inner observable, meaning that this will be the person, and this will be the homeworld response.

    This guy gets passed here, and this guy gets passed here, which will let us merge together a props object. We want everything off the person, and then the homeworld, we want to be the

    We're passing in ID, not, so delete that there. Hit save, and you can see we get John, Earth, Luke Skywalker, Tatooine. Now, one trick we can do here is on the second request, I can say start with an object with a name of an empty string, which when I save will allow Luke Skywalker to load, and then Tatooine to load.

    It'll give us the data as available. You'll see this again, Luke and then Tatooine. The data can stream in as it's received.