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.
- Make the actual request
- 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:
- Simply get call using Axios
- Calling a GET request using Axios with async-await
- Calling a POST request using Axios
- 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 command line interface to make our React Native App.
If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:
npm uninstall -g react-native-cli @react-native-community/cli
Run the following commands to create a new React Native project
npx react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
npx react-native init ProjectName --version X.XX.X
Note If the above command is failing, you may have old version of react-native
or react-native-cli
installed globally on your pc. Try uninstalling the cli and run the cli using npx.
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
// React Native Axios – To Make HTTP API call in React Native
// https://aboutreact.com/react-native-axios/
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.container}>
<Text style={{fontSize: 30, textAlign: 'center'}}>
Example of Axios Networking in React Native
</Text>
{/*Running GET Request*/}
<TouchableOpacity
style={styles.buttonStyle}
onPress={getDataUsingSimpleGetCall}>
<Text>Simple Get Call</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.buttonStyle}
onPress={getDataUsingAsyncAwaitGetCall}>
<Text>Get Data Using Async Await GET</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.buttonStyle}
onPress={postDataUsingSimplePostCall}>
<Text>Post Data Using POST</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.buttonStyle}
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({
container: {
justifyContent: 'center',
flex: 1,
padding: 16,
},
buttonStyle: {
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
1. Start Metro Bundler
First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:
npx react-native start
Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.
2. Start React Native Application
To run the project on an Android Virtual Device or on real debugging device:
npx react-native run-android
or on the iOS Simulator by running (macOS only)
npx react-native run-ios
Output Screenshots
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. 🙂
Thank you so much for making this! It’s simple, straightforward, easy to follow….and it works! Thanks again!
Welcome 🙂
I copy this but it doesn’t work! why?
Any Error reporting? What you are seeing problematic?
Hii
When i give build release when hit http call from axios app is getting hard crash, i dont know where i am getting this issue,
Any crash reporting? Any hint or any log?
Thank you so for your code. it’s very simple and efficient.
Thankyou its very helpfull for me.