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.


    Fetch Data from an HTTP Server in a React Native Application using fetch or axios

    react-nativeReact Native

    In this lesson we’ll use fetch to get data from an HTTP server, and store it in state in our React Native application. fetch works almost identically on the web and React Native - with the possible exception of how it handles cookies. We’ll also take a look at axios - which is an alternative to fetch.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    Instructor: Let's remove this hard-coded list of restaurants and add a componentDidMount lifecycle method, where we want to make an HTTP call. We can use Fetch in React Native just like on the web. I'll make a call to a small local server that I have running that will return a list of restaurants.

    On the iOS simulator, I can use localhost, but on the Android emulator, it has its own IP address, so localhost will not refer to my PC. Instead of localhost here, you will need your computer's IP address on your local network.

    The restaurant's return is JSON, so just like on the web, we have to parse that response as JSON. Then we can use the result. In this case, that means by setting local state.

    Let's make sure that state starts as an empty array. Then we can use the state, instead of the old hard-coded list, as the data for FlatList.

    When we reload that, we see the HTTP call being made and then the list of restaurants pop into place. Fetch is built in and works great in most cases, but you may want an additional option. In particular, I've had trouble with how Fetch handles cookies on React Native.

    Let's npm install Axios, which is an alternative to Fetch. We can import Axios from Axios and use it instead of Fetch to make an HTTP request. Axios parses the response as JSON by default, so we don't need to parse the results anymore. The result comes back as an object. To get the restaurants here, we'll have to access the data key on that object.

    When we reload now, we're using Axios to do the HTTP get request.