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.
Instructor: [00:00] 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.
[00:22] We'll use our personById function, and pass in the props.id. 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.
[00:41] 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.
[01:01] Props.id 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.
[01:24] 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.
[01:42] 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 homeworld.name.
[01:55] We're passing in ID, not props.id, 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.
[02:20] 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.
Thanks for the course, would be great if it can be updated with the new rxjs API