The way you make HTTP requests in React Native is with the Fetch API. In this video we'll talk about Fetch and how to work with promises.
If you've ever used the XML HTTP request API, it's pretty archaic. It's pretty weird. Odds are you've used Angular's HTTP service before, or you've used something like Axios or any other library that allows you to make XHR requests. Another one, a very popular one, is obviously jQuery's AJAX.
What React Native utilizes is this thing called "fetch." The fetch API has been available in the service worker global since Chrome 40, but it'll be enabled in the Windows scope in Chrome 42. Currently, I'm running this in Chrome Canary, which means we have fetch available, but it's not currently in Chrome yet.
What fetch is is it's similar to XML HTTP requests, in the sense where it allows you to make these HTTP requests, but it's promise-based. The API for it is a little more clean. What we're going to do is if we had a URL...
We're going to use the GitHub API. The endpoint we're going to hit is api.github.com/users/ just my user name. Then what we can do is if we run or if we invoke fetch, you'll notice that what that returns us is a promise.
Now, instead of having to worry about these callbacks, we're going to get a promise back, that we can then chain this .then on. The way I like to think about it if you're new to promises and the way you can think about it is we invoke this fetch function.
When fetch has finished requesting our data from this URL, it will invoke the function that's inside the .then method. We can also do something like this, where if there's an error, it will invoke this catch method and give us back this error. We'll console.log there. Here, we'll console.log the response.
Notice we have this response object. It has some stuff on it. This isn't actually the exact data we want though. What we're going to do is we're going to modify this a little bit to say, "Once we get this response back, let's go ahead and return res.json."
This is going to parse our JSON and return us another promise that we can chain under here. Pass in another function. Now, this response should be our...Let's call it our "JSON response." From here, let's console.log the response.
Now, what should happen...We have a syntax error. There we go. Notice what happened was we call fetch. We had a .then under that. This function will run. Once our initial data gets back from the GitHub servers, then we're going to return another promise so we can then chain it again. Then we console.log the response, which is the data that we wanted from GitHub.
If we go in here and we change this URL to be something that's broken...Let's just do github.com/ whatever. You'll notice we get an error because it caught the error. That's how you make HTTP requests with React Native, is fetch. Even though it's not available in the browser yet, it is available with React Native.