Axios in React Native

Last Updated : 18 Feb, 2026

Axios in React Native is a popular promise-based HTTP client used to make network requests from a React Native app to APIs. It simplifies sending and receiving data compared to the built-in fetch API.

  • Used to perform GET, POST, PUT, DELETE requests to backend servers or REST APIs.
  • Provides automatic JSON data transformation, making it easier to handle API responses.
  • Supports interceptors, request cancellation, and error handling, improving control over network calls.
JavaScript
// Simple Example (GET request)

import React, { useEffect } from 'react';
import { View, Text } from 'react-native';
import axios from 'axios';

const App = () => {

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/users/1')
      .then(response => {
        console.log(response.data.name);
      })
      .catch(error => {
        console.log(error);
      });
  }, []);

  return (
    <View>
      <Text>Check console for Axios output</Text>
    </View>
  );
};

export default App;
  • axios.get() sends a GET request to the API.
  • response.data contains the data from the server.
  • .catch() handles errors if the request fails.

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

  • Promise-based API – Uses async/await and .then() for easier asynchronous handling.
  • Supports all HTTP methods – GET, POST, PUT, PATCH, DELETE.
  • Automatic JSON conversion – Converts request and response data to JSON automatically.
  • Interceptors support – Modify requests or responses globally (e.g., add auth tokens).
  • Error handling – Provides detailed error information for failed requests.
  • Request cancellation – Cancel ongoing requests to save resources.
  • Timeout support – Set time limits for API requests.
  • Works with REST APIs easily – Simplifies communication with backend servers.

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

GET Request in Axios (React Native) is used to retrieve data from a server or API. The axios.get() method sends a request to the specified URL and returns the response.

  • Used to fetch data from an API by providing the URL and optional parameters.
  • The response contains data, status, and headers if the request is successful.
  • Errors are handled using .catch(), and .finally() can run code after completion.
JavaScript
import React, { useEffect } from 'react';
import { View, Text } from 'react-native';
import axios from 'axios';

const App = () => {

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/posts/1')
      .then(response => {
        console.log("Title:", response.data.title);
      })
      .catch(error => {
        console.log("Error:", error);
      })
      .finally(() => {
        console.log("Request completed");
      });
  }, []);

  return (
    <View>
      <Text>Check console for GET request result</Text>
    </View>
  );
};

export default App;
  • axios.get(URL) fetches data from the API.
  • response.data contains the fetched data.
  • .catch() handles errors and .finally() runs after completion.

Syntax

axios.get(url, {
params: {
key1: value1,
key2: value2
}
})
.then(response => {
// handle success
})
.catch(error => {
// handle error
})
.finally(() => {
// runs every time
});
  • url : API endpoint to fetch data from.
  • params : Optional parameters sent with the request.
  • .then() : Executes when request is successful.
  • .catch() : Executes if an error occurs.
  • .finally() : Executes after request completes (success or error).

POST Request

POST Request is used to send data from your React Native app to a server or API. The axios.post() method sends data in the request body and returns the response.

  • Used to send data to a server, such as form data or user information.
  • The request body contains the data, and the server returns a response.
  • Errors are handled using .catch(), and .finally() runs after completion.
JavaScript
import React, { useEffect } from 'react';
import { View, Text } from 'react-native';
import axios from 'axios';

const App = () => {

  useEffect(() => {
    axios.post('https://jsonplaceholder.typicode.com/posts', {
      title: 'Hello',
      body: 'This is a POST request',
      userId: 1
    })
    .then(response => {
      console.log("Response:", response.data);
    })
    .catch(error => {
      console.log("Error:", error);
    })
    .finally(() => {
      console.log("POST request completed");
    });
  }, []);

  return (
    <View>
      <Text>Check console for POST request result</Text>
    </View>
  );
};

export default App;
  • axios.post() sends data to the server.
  • The object { title, body, userId } is the request data.
  • response.data contains the server response.

Syntax

axios.post(url, data, {
headers: {
key: value
}
})
.then(response => {
// handle success
})
.catch(error => {
// handle error
})
.finally(() => {
// runs every time
});
  • url : API endpoint.
  • data : Information you want to send to the server.
  • headers : Optional request headers.

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.

1. 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.

2. For iOS users, simply scan the QR code using the Camera app.

3. 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.

JavaScript
// 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.

JavaScript
// 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.

JavaScript
// Function to fetch advice from the API
const getAdvice = () => {
    axios
        .get("https://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.

JavaScript
// 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.

JavaScript
<Button 
    title="Get Advice"
    onPress={getAdvice}
    color="green" 
/>

- Text: This component is used to display the response coming from the getAdvice method.

JavaScript
<Text style={styles.advice}>{advice}</Text>

- useState: This is used to declare a state variable 'advice' to store the advice text and update it.

JavaScript
// 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:

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("https://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

Comment

Explore