Comments

Make API Calls in React Native Using Fetch

Your mobile app most likely needs to load resources from a remote URL at some point. Making calls over the network is a common use-case that you will handle while developing any app. React Native comes with a Fetch API, that is used to make API calls to the server.

Fetch

The Fetch API provides a JavaScript interface that can fetch resources asynchronously over the network. It is very similar to the XMLHttpRequestthat is used for the same purpose. But the fetch API is powerful and flexible.

Request Data with Fetch

In React Native, you can request data from an API over the network using the fetch() method.

The syntax is simple as follows:

fetch('https://examples.com/data.json');

We simply pass the URL to the fetch method to make a request.

In addition to the URL, fetch can also take an optional second argument. This is where you can customize the HTTP request.

fetch('https://examples.com/data.json', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    firstParam: 'yourValue'
  })
});

In the above code snippet, the first argument to the fetch() method is the URL, followed by the additional second argument. To the request object we have passed properties such as methodheaders and body. The method is used to determine if the request is a GET, POST, etc.. The body is a simple getter that exposes the body content in JSON format.

We can also pass other properties to the request object like cache, context, credentials, headers and so on. You can read Request for Fetch API to learn more about the properties supported by the Request interface.

Handle Response from Fetch

Once a request is made to the server, the server gets back with a response. Our React Native app needs to handle this response from the server.

Sending a request and waiting for a response back is asynchronous in nature and and we can wrap the fetch call in React Native within an async-await function as shown below.

const getArticlesFromApi = async () => {
    let response = await fetch(
      'https://examples.com/data.json'
    );
    let json = await response.json();
    return json.movies;
  }
};

In the above code snippet, we await for the response to be returned. The response JSON object is then extracted and returned back. If you have not used async/await functions in JavaScript, make sure to read my article: How to Use async/await in JavaScript?

Handle Errors

While communicating with APIs over the network, we also need to account for handling any errors that may occur. We can efficiently handle errors and either let the user know that an error has occurred or log them on the console if necessary.

Add a try and catch block to our code snippet to catch any errors thrown.

const getArticlesFromApi = async () => {
    try {
      let response = await fetch(
        'https://examples.com/data.json'
      );
      let json = await response.json();
      return json.movies;
    } catch (error) {
       console.error(error);
    }
  };

We have wrapped our fetch call in a try and catch block above and logged the error on the console.

React Native Example in Fetching Data

We are now going to retrieve data from a json file in a sample React Native project. The content of the json file can be found here: testAPI.json

The file contains a title, description and an array of articles. Each article has an id and title. We want to display the list of articles in our React Native app, along with its id. To do this we can follow the steps summarized below:

Steps to fetch data:

  1. Pass the URL to the fetch API. The URL will be the same as above that contains the testAPI.json file.
  2. Next we will parse the response object and extract the json response that is obtained.
  3. UI will display the data response.
  4. Catch any errors thrown from the fetch call.

The example is written as an expo snack that you can play with here and you can also run it on an iOS or Android simulator by clicking the code snippet below:

We are using a functional React component in our example. I want to fetch the data as soon as the component mounts, and the best place to fetch would be in the useEffect hook. I am using two state variables, isLoading and data. The data holds the json response from the API and the isLoading holds the status of the call.

Let’s analyze what is happening within the useEffect hook:

 useEffect(() => {
    fetch('https://raw.githubusercontent.com/adhithiravi/React-Hooks-Examples/master/testAPI.json')
      .then((response) => response.json())
      .then((json) => setData(json))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, []);

The useEffect hook is similar to the componentDidMount and componentDidUpdate in class components. Learn more about the useEffect hook from my previous article: Guide to Learn useEffect Hook in React

The fetch call is passed the URL, the response is then parsed. The setData is used to to set the state of the data which contains the response json. The data state can be used throughout the component. Errors are then handled. The finally block is executed after the call is complete, and it sets the isLoading state to false.

Render UI

Now the component parses the data and renders it using a FlatList component. The resulting UI is shown below:

You can see that our mobile app parses the JSON response and displays the articles list in the UI. When there is an error, it will log it to the console. And if the data is not loaded yet, we will display a “Loading..” message. Quite neat isn’t it?!

Conclusion

Alright, that’s a wrap folks. To read the official documentation from React Native on fetch checkout the link below:

https://reactnative.dev/docs/network

The example used in this blog post can be accessed from my expo snack below:

React Native Fetch Example by Adhithi Ravichandran

If you are looking for a course that teaches your React Native from start to finish, checkout Mosh’s course linked below:

Ultimate React Native Course – Code With Mosh

I hope you enjoyed this article. See you again with more articles. If you liked this post, don’t forget to share it with your network. You can follow me on twitter @AdhithiRavi for more updates or if you have any questions.

Adhithi Ravichandran is a Software Consultant based in Kansas City. She is currently working on building apps with React, React Native and GraphQL. She is a Conference Speaker, Pluralsight Author, Blogger and Software Consultant. She is passionate about teaching and thrives to contribute to the tech community with her courses, blog posts and speaking engagements.
Tags: , , , ,

One response to “Make API Calls in React Native Using Fetch”

  1. Binod Raj Dhami says:

    Now I am clear about fetching in React Native, thanks a lot for sharing thing topic. I learnt many things in your React Native course and make new course React Native using CLI.

Leave a Reply

Connect with Me
  • Categories
  • Popular Posts

    %d bloggers like this: