Axios in React Native
Axios is a widely used HTTP client for making REST API calls. You can use this in React Native to get data from any REST API.
Axios in React Native
Axios is a library that helps you send HTTP requests in React Native apps. It allows mobile devices to communicate with a server, enabling them to send and receive data through API endpoints. This means that when you want to get information from a server or send information to it, Axios makes it easier to do so.
Syntax
// GET Request
axios.get(url, config)
// POST Request
axios.post(url, data, config)
// PUT Request
axios.put(url, data, config)
// DELETE Request
axios.delete(url, config)
// PATCH Request
axios.patch(url, data, config)
Features
- It can make both XMLHttpRequests and HTTP requests.
- It can understand all the requests and responses from an API.
- Axios is promise-based.
- It can transform the response into JSON format.
To make the most of Axios, understanding the flow of asynchronous requests is crucial.
Install Axios in React Native
You can install Axios in your React Native project with either npm or yarn. Open the terminal on your computer and go to your project directory.
Using npm:
npm install axios
Using yarn:
yarn add axios
You can make both GET and POST requests with Axios in React Native:
- The GET request is used to get data from an API.
- The POST request is used to modify the data on the API server.
GET Request
The axios.get() method is used to perform GET requests in Axios with React Native. It takes a base URL to get data. You can specify parameters that you want to pass with the base URL, with params.
If it gets executed successfully, you will get a response. This response will contain data and other information regarding the request. If any error occurs, then the catch statement will catch that error.
If you want something to execute every time, in that case, you can write that under the statement.
Syntax
axios.get('/GeeksforGeeks', {
params: {
articleID: articleID
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
POST Request
The axios.post() method is a way to send data to a server using POST requests in React Native. This method is part of the Axios library, which helps you make HTTP requests easily. You can specify parameters that you want to pass with the base URL through an object.
If it gets executed successfully, you will get a response. This response will contain of data and other information regarding the request.
If any error occurs, then the catch statement will catch that error.
axios.post('/GeeksforGeeks', {
articleID: 'articleID',
title: 'Axios in React Native'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Step-by-Step Implementation
Step 1: Create a React Native Project
Now, create a project with the following command.
npx create-expo-app app-name --template
Note: Replace the app-name with your app name for example : react-native-demo-app
Next, you might be asked to choose a template. Select one based on your preference as shown in the image below. I am selecting the blank template because it will generate a minimal app, as clean as an empty canvas in JavaScript.

It completes the project creation and displays a message: "Your Project is ready!" as shown in the image below.

Now go into your project folder, i.e., react-native-demo
cd app-name
Project Structure:

Step 2: Run Application
Start the server by using the following command.
npx expo start
Then, the application will display a QR code.
- For the Android users,
- For the Android Emulator, press "a" as mentioned in the image below.
- For the Physical Device, download the "Expo Go" app from the Play Store. Open the app, and you will see a button labeled "Scan QR Code." Click that button and scan the QR code; it will automatically build the Android app on your device.
- For iOS users, simply scan the QR code using the Camera app.
- If you're using a web browser, it will provide a local host link that you can use as mentioned in the image below.

Step 3: Start Coding'
- Import libraries: Import required libraries at the top of the file.
// Importing the useState hook from React
import { useState } from "react";
// Importing necessary components from React Native
import {
StyleSheet, // for styling components
View, // for creating a container
Text, // for displaying text
Button // for creating a button
} from "react-native";
// Importing axios for making HTTP requests
import axios from "axios";
- StyleSheet: Create a StyleSheet to style components like container and advice.
// Defining styles for the components
const styles = StyleSheet.create({
container: {
flex: 1, // Makes the container take up the full screen
backgroundColor: "#fff", // Sets the background color to white
alignItems: "center", // Centers content horizontally
justifyContent: "center", // Centers content vertically
},
advice: {
fontSize: 20, // Sets the font size for the advice text
fontWeight: "bold", // Makes the advice text bold
marginHorizontal: 20, // Adds horizontal margin to the advice text
},
});
We will make a GET request with Axios in React Native. We will use the Advice Slip API for this example. This API takes id as parameters and provides advice associated with that id.
- getAdvice: This function is to make a GET request and update the state.
// Function to fetch advice from the API
const getAdvice = () => {
axios
.get("http://api.adviceslip.com/advice/" +
getRandomId(1, 200)) // Fetching advice using a random ID
.then((response) => {
// Updating the 'advice' state with the fetched advice
setAdvice(response.data.slip.advice);
});
};
We will declare a function that randomly generates 1 id and we will pass this id in params in Axios GET request.
- getRandomId: This function is to generate a random ID within min and max every time.
// Function to generate a random ID between a given range (min and max)
const getRandomId = (min, max) => {
min = Math.ceil(min); // Ensuring min is rounded up
max = Math.floor(max); // Ensuring max is rounded down
// Returning a random integer between min and max (inclusive) as a string
return (Math.floor(Math.random() *
(max - min + 1)) + min).toString();
};
There will be 2 components in our main App.js file: Text and Button. When you press the button, Axios will make a GET request to the advice slip API and fetch one random advice. Later on, we will display this advice on the screen using a Text component.
- Button: This component interact with the user and when user click on it, it will call the getAdvice method.
<Button
title="Get Advice"
onPress={getAdvice}
color="green"
/>
- Text: This component is used to display the response coming from the getAdvice method.
<Text style={styles.advice}>{advice}</Text>
- useState: This is used to declare a state variable 'advice' to store the advice text and update it.
// Declaring a state variable 'advice' to store the advice text
const [advice, setAdvice] = useState("");
Now, wrap the Button and Text components with a View component and return from the App component. Also, ensure to export the App.
App.js:
// Importing the useState hook from React
import { useState } from "react";
// Importing necessary components from React Native
import {
StyleSheet, // for styling components
View, // for creating a container
Text, // for displaying text
Button // for creating a button
} from "react-native";
// Importing axios for making HTTP requests
import axios from "axios";
// Defining the main App component
export default function App() {
// Declaring a state variable 'advice' to store the advice text
const [advice, setAdvice] = useState("");
// Function to generate a random ID between a given range (min and max)
const getRandomId = (min, max) => {
min = Math.ceil(min); // Ensuring min is rounded up
max = Math.floor(max); // Ensuring max is rounded down
// Returning a random integer between min and max (inclusive) as a string
return (Math.floor(Math.random() *
(max - min + 1)) + min).toString();
};
// Function to fetch advice from the API
const getAdvice = () => {
axios
.get("http://api.adviceslip.com/advice/" +
getRandomId(1, 200)) // Fetching advice using a random ID
.then((response) => {
// Updating the 'advice' state with the fetched advice
setAdvice(response.data.slip.advice);
});
};
// Rendering the UI
return (
<View style={styles.container}>
{/* Displaying the fetched advice */}
<Text style={styles.advice}>{advice}</Text>
{/* Button to trigger the getAdvice function */}
<Button title="Get Advice"
onPress={getAdvice} color="green" />
</View>
);
}
// Defining styles for the components
const styles = StyleSheet.create({
container: {
flex: 1, // Makes the container take up the full screen
backgroundColor: "#fff", // Sets the background color to white
alignItems: "center", // Centers content horizontally
justifyContent: "center", // Centers content vertically
},
advice: {
fontSize: 20, // Sets the font size for the advice text
fontWeight: "bold", // Makes the advice text bold
marginHorizontal: 20, // Adds horizontal margin to the advice text
},
});
Output
Summary
Axios is a promise based http client used in React native to communicate to the server. It is used to send the http request like get and post and also send and receive the data with the help of API endpoints.