React Native Axios – To Make HTTP API call in React Native

React Native Axios

Axios is a Javascript library used to make HTTP requests and it supports the Promise API that is native to JS ES6. If you are using React Native Fetch to make HTTP API calls in React Native then Axios is the other option that you can explore. You can make any HTTP calls using Axios in React Native.

Similar to fetch, Axios also provides you the facility to call GET, POST, PUT, PATCH, and DELETE requests. Axios also has more options and features to call the API as compared to fetch. One feature you can see in one sight is that it performs automatic transforms of JSON data. If you use .fetch() there is a two-step process when handling JSON data.

  1. Make the actual request
  2. Call the .json() method on the response to get the data in JSON

You can google fetch vs Axios and can read articles justifies why to use Axios over fetch but what I personally want to share is the [Question] what advantage does axios give us over fetch?, this is the question asked on Axios’s GitHub repository where many different developers have shared their personal opinions (I personally like to hear from the developers like me, not from the shiny paid posts).

I do not say to use Axios or fetch because I personally used both in big projects and they both are working fine with no performance difference (until and unless you are making a project where some milliseconds can make the difference).

Code Snippet of Basic Network Call using Axios

Here is a small code snippet showing how to use Axios in the React Native project for the HTTP request. Here you can see that we have used axis with the get request with the ‘WEB URL’ and after that getting the response in a function using a callback. You will find a catch attached to it which will trigger a function in case of any failure. There is an additional finally callback which will trigger a function after the completion of API call.


axios.get('Web URL')
.then(function(response) {
    // handle response
}).catch(function(error) {
    // handle error
}).finally(function() {
    // always executes at the last of any API call
});

Axios Example Description

In this example, we are going to use free demo APIs for the demo API call. If we talk about the UI then we will have 4 buttons which will different functions to perform below-mentioned operations using the Axios:

  1. Simply get call using Axios
  2. Calling a GET request using Axios with async-await
  3. Calling a POST request using Axios
  4. Multiple concurrent requests in a single call

I hope you will have a proper understanding of Axios after this. If you want to add some point feel free to share with me.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

This will make a project structure with an index file named App.js in your project directory.

Installation of Dependencies

To use axios you need to install axios dependency and to do that open the terminal and jump into the project using

cd ProjectName

Run the following commands

npm install --save axios

This command will copy all the dependencies into your node_module directory. –save is optional, it is just to update the dependency in your package.json file.

Code To Make HTTP API call in React Native using Axios

Open App.js in any code editor and replace the code with the following code

App.js

//To Make HTTP API call in React Native using Axios https://aboutreact.com
import React from 'react';
//import React in our code.
import { StyleSheet, View, TouchableOpacity, Text } from 'react-native';
//import all the components we are going to use.
import axios from 'axios';

const App = () => {
  const getDataUsingSimpleGetCall = () => {
    axios
      .get('https://jsonplaceholder.typicode.com/posts/1')
      .then(function(response) {
        // handle success
        alert(JSON.stringify(response.data));
      })
      .catch(function(error) {
        // handle error
        alert(error.message);
      })
      .finally(function() {
        // always executed
        alert('Finally called');
      });
  };

  const getDataUsingAsyncAwaitGetCall = async () => {
    try {
      const response = await axios.get(
        'https://jsonplaceholder.typicode.com/posts/1'
      );
      alert(JSON.stringify(response.data));
    } catch (error) {
      // handle error
      alert(error.message);
    }
  };

  const postDataUsingSimplePostCall = () => {
    axios
      .post('https://jsonplaceholder.typicode.com/posts', {
        title: 'foo',
        body: 'bar',
        userId: 1,
      })
      .then(function(response) {
        // handle success
        alert(JSON.stringify(response.data));
      })
      .catch(function(error) {
        // handle error
        alert(error.message);
      });
  };

  const multipleRequestsInSingleCall = () => {
    axios
      .all([
        axios
          .get('https://jsonplaceholder.typicode.com/posts/1')
          .then(function(response) {
            // handle success
            alert('Post 1 : ' + JSON.stringify(response.data));
          }),
        axios
          .get('https://jsonplaceholder.typicode.com/posts/2')
          .then(function(response) {
            // handle success
            alert('Post 2 : ' + JSON.stringify(response.data));
          }),
      ])
      .then(
        axios.spread(function(acct, perms) {
          // Both requests are now complete
          alert('Both requests are now complete');
        })
      );
  };

  return (
    <View style={styles.MainContainer}>
      <Text style={{ fontSize: 30, textAlign: 'center' }}>
        Example of Axios Networking in React Native
      </Text>
      {/*Running GET Request*/}
      <TouchableOpacity
        style={styles.button}
        onPress={getDataUsingSimpleGetCall}>
        <Text>Simple Get Call</Text>
      </TouchableOpacity>

      <TouchableOpacity
        style={styles.button}
        onPress={getDataUsingAsyncAwaitGetCall}>
        <Text>Get Data Using Async Await GET</Text>
      </TouchableOpacity>

      <TouchableOpacity
        style={styles.button}
        onPress={postDataUsingSimplePostCall}>
        <Text>Post Data Using POST</Text>
      </TouchableOpacity>

      <TouchableOpacity
        style={styles.button}
        onPress={multipleRequestsInSingleCall}>
        <Text>Multiple Concurrent Requests In Single Call</Text>
      </TouchableOpacity>

      <Text style={{ textAlign: 'center', marginTop: 18 }}>
        www.aboutreact.com
      </Text>
    </View>
  );
};

const styles = StyleSheet.create({
  MainContainer: {
    justifyContent: 'center',
    flex: 1,
    padding: 16,
  },
  button: {
    alignItems: 'center',
    backgroundColor: '#DDDDDD',
    padding: 10,
    width: '100%',
    marginTop: 16,
  },
});

export default App;

To Run the React Native App

Open the terminal again and jump into your project using.
cd ProjectName
To run the project on an Android Virtual Device or on real debugging device
react-native run-android
or on the iOS Simulator by running
react-native run-ios (macOS only).

Output Screenshots

React Native Axis 1    .    

This is how you can make HTTP API call in React Native using Axios. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂


Related Posts

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.