Lesson 52 of 60 – Axios in React Native
87%

Axios in React Native

Axios is a popular JavaScript library used to make HTTP requests from React Native applications. It can be used to communicate with REST APIs and backend servers.

With Axios, you can perform common operations such as GET, POST, PUT and DELETE requests.

React Native App
       ↓
      Axios
       ↓
   REST API
       ↓
     Server
       ↓
   JSON Data
       ↓
React Native App
Note: Axios is an external package, unlike the Fetch API which is available through the JavaScript platform. Axios provides a convenient API for working with HTTP requests.

1. What is Axios?

Axios is a Promise-based HTTP client that can be used to send requests to web servers and APIs.

A React Native application can use Axios to retrieve or send data to a backend server.

axios.get(url);

2. Why Use Axios?

Axios provides a convenient way to work with HTTP requests.

  • GET requests
  • POST requests
  • PUT requests
  • PATCH requests
  • DELETE requests
  • Request headers
  • Request configuration
  • Error handling

3. Installing Axios

Axios needs to be installed in the React Native project.

npm install axios

After installation, Axios can be imported into JavaScript or TypeScript files.

4. Importing Axios

Import Axios before using it.

import axios from "axios";

You can now use Axios methods such as axios.get() and axios.post().

5. Basic Axios GET Request

The get() method is used to retrieve data.

axios.get(
    "https://example.com/api/users"
)
.then(response => {

    console.log(response.data);

});

Axios provides the response data through response.data.

6. Axios with async and await

Axios works well with async and await.

async function loadUsers() {

    const response =
        await axios.get(
            "https://example.com/api/users"
        );

    console.log(response.data);

}

This style can make asynchronous API code easier to read.

7. Axios Response Object

Axios returns a response object containing information about the request and server response.

const response =
    await axios.get(url);

console.log(response.data);
console.log(response.status);
console.log(response.headers);

The data property is commonly used to access the returned API data.

8. Storing Axios Data with useState

API data can be stored in React state.

const [users, setUsers] =
    useState([]);

async function loadUsers() {

    const response =
        await axios.get(url);

    setUsers(response.data);

}

9. Axios with useEffect

Axios can be used inside useEffect() when data should be loaded when a screen starts.

useEffect(() => {

    loadUsers();

}, []);

The function can request data and update the component state.

10. Complete Axios GET Example

import React, {
    useEffect,
    useState
} from "react";

import axios from "axios";

function UsersScreen() {

    const [users, setUsers] =
        useState([]);

    async function loadUsers() {

        const response =
            await axios.get(
                "https://example.com/api/users"
            );

        setUsers(response.data);

    }

    useEffect(() => {

        loadUsers();

    }, []);

}

11. Axios POST Request

The post() method is used to send data to a server.

axios.post(
    "https://example.com/api/users",
    {
        name: "Rahul",
        email: "rahul@example.com"
    }
);

The second argument contains the request body.

12. POST Request with async and await

async function createUser() {

    const response =
        await axios.post(
            "https://example.com/api/users",
            {
                name: "Rahul",
                email: "rahul@example.com"
            }
        );

    console.log(response.data);

}

13. Axios PUT Request

The put() method can be used to update existing data.

axios.put(
    "https://example.com/api/users/10",
    {
        name: "Rahul Kumar"
    }
);

The exact behavior depends on how the backend API implements PUT.

14. Axios PATCH Request

The patch() method is commonly used when only part of a resource needs to be updated.

axios.patch(
    "https://example.com/api/users/10",
    {
        name: "Rahul Kumar"
    }
);

15. Axios DELETE Request

The delete() method is used to request deletion of a resource.

axios.delete(
    "https://example.com/api/users/10"
);

The server determines whether the requested deletion is permitted.

16. Axios Error Handling

Use try...catch to handle errors when using Axios with async and await.

try {

    const response =
        await axios.get(url);

    console.log(response.data);

} catch (error) {

    console.log(error);

}

17. Creating an Error State

An error message can be stored in state.

const [error, setError] =
    useState("");

try {

    const response =
        await axios.get(url);

    setUsers(response.data);

} catch (error) {

    setError(
        "Unable to load users"
    );

}

18. Loading State with Axios

A loading state can indicate that an Axios request is currently running.

const [loading, setLoading] =
    useState(true);

async function loadUsers() {

    try {

        setLoading(true);

        const response =
            await axios.get(url);

        setUsers(response.data);

    } finally {

        setLoading(false);

    }

}

19. Displaying ActivityIndicator

The ActivityIndicator component can be displayed while Axios is loading data.

{loading ? (

    <ActivityIndicator />

) : (

    <Text>
        Data Loaded
    </Text>

)}

20. Sending Request Headers

Axios allows you to send HTTP headers with a request.

axios.get(url, {

    headers: {

        "Content-Type":
            "application/json"

    }

});

Headers can contain information required by an API.

21. Axios POST Headers

axios.post(
    url,

    {
        name: "Rahul"
    },

    {
        headers: {
            "Content-Type":
                "application/json"
        }
    }
);

The third argument can contain Axios request configuration.

22. Axios for Login

Axios can be used to send login credentials to a backend API.

async function login() {

    const response =
        await axios.post(
            "https://example.com/api/login",
            {
                email: email,
                password: password
            }
        );

    console.log(response.data);

}

The server can validate the credentials and return an authentication response.

23. Axios for Fetching Course Data

An education application can use Axios to load courses from an API.

async function loadCourses() {

    try {

        const response =
            await axios.get(
                "https://example.com/api/courses"
            );

        setCourses(
            response.data
        );

    } catch (error) {

        console.log(error);

    }

}

24. Axios with FlatList

Axios data can be displayed using FlatList.

<FlatList
    data={users}
    keyExtractor={
        item =>
        item.id.toString()
    }
    renderItem={({ item }) => (

        <Text>
            {item.name}
        </Text>

    )}
/>

This is useful when an API returns a list of records.

25. Creating an Axios Instance

For larger applications, you can create an Axios instance with common configuration.

import axios from "axios";

const api =
    axios.create({

        baseURL:
            "https://example.com/api",

        timeout: 10000

    });

export default api;

The instance can then be reused throughout the application.

26. Common Axios Mistakes

  • Forgetting to install Axios.
  • Forgetting to import Axios.
  • Using the wrong API URL.
  • Not handling request errors.
  • Not displaying a loading state.
  • Using incorrect HTTP methods.
  • Sending incorrect request data.
  • Ignoring API response status.
  • Repeating the same API configuration throughout the project.

27. Complete Axios Example

import React, {
    useEffect,
    useState
} from "react";

import {
    View,
    Text,
    ActivityIndicator,
    FlatList
} from "react-native";

import axios from "axios";

export default function UsersScreen() {

    const [users, setUsers] =
        useState([]);

    const [loading, setLoading] =
        useState(true);

    const [error, setError] =
        useState("");

    async function loadUsers() {

        try {

            setLoading(true);
            setError("");

            const response =
                await axios.get(
                    "https://example.com/api/users"
                );

            setUsers(
                response.data
            );

        } catch (error) {

            setError(
                "Unable to load users"
            );

        } finally {

            setLoading(false);

        }

    }

    useEffect(() => {

        loadUsers();

    }, []);

    if (loading) {

        return (
            <ActivityIndicator />
        );

    }

    if (error) {

        return (
            <Text>
                {error}
            </Text>
        );

    }

    return (

        <FlatList
            data={users}
            keyExtractor={
                item =>
                item.id.toString()
            }
            renderItem={({ item }) => (

                <View>

                    <Text>
                        {item.name}
                    </Text>

                </View>

            )}
        />

    );

}

This example combines Axios, useEffect, useState, error handling, loading handling and FlatList.

28. Axios Best Practices

  • Keep API calls organized in service functions.
  • Use an Axios instance for common API configuration.
  • Handle loading and error states.
  • Use async and await when it improves readability.
  • Keep API URLs organized.
  • Use HTTPS for production APIs.
  • Do not place sensitive secrets directly in the mobile application.
  • Keep authentication and authorization responsibilities clear.
  • Reuse common request configuration where appropriate.

29. Important Axios Concepts

Concept Purpose
axios.get() Retrieves data from an API
axios.post() Sends data to an API
axios.put() Updates a resource
axios.patch() Partially updates a resource
axios.delete() Requests deletion of a resource
response.data Contains the response body
response.status Contains the HTTP status code
axios.create() Creates a reusable Axios instance

30. Complete Axios Workflow

React Native Screen
        ↓
Call API Function
        ↓
Axios Request
        ↓
Backend API
        ↓
Server Response
        ↓
Read response.data
        ↓
Update State
        ↓
Render UI

If Request Fails
        ↓
Catch Error
        ↓
Update Error State
        ↓
Show Error Message

Axios provides a convenient way to communicate with APIs from React Native applications. It supports common HTTP methods, request configuration, response handling and error handling.

📌 Key Points

  • Axios is an HTTP client used for API communication.
  • Install Axios using npm install axios.
  • Import Axios using import axios from "axios".
  • Use axios.get() to retrieve data.
  • Use axios.post() to send data.
  • Use axios.put() and axios.patch() to update data.
  • Use axios.delete() to request deletion.
  • Use response.data to access response data.
  • Use loading and error states for a better user experience.
  • Axios can be combined with useEffect and useState.
  • Axios instances can organize common API configuration.
  • Axios is useful for connecting React Native applications to REST APIs.

🧠 Quick Quiz

Question: Which Axios method is commonly used to retrieve data from an API?