Lesson 47 of 60 – Axios with React
78%

Axios with React

Axios is a JavaScript library used to make HTTP requests. In React applications, Axios can be used to communicate with APIs and retrieve, create, update, or delete data from a server.

Note: Axios provides a convenient API for making HTTP requests. It can be used with React Hooks such as useEffect and useState when working with API data.

1. What is Axios?

Axios is a Promise-based HTTP client for JavaScript applications.

It can be used to communicate with APIs and web servers.

React
  ↓
Axios
  ↓
API
  ↓
Server

2. Why Use Axios?

Axios makes HTTP requests convenient and provides features that are useful when working with APIs.

It can be used for:

  • GET requests
  • POST requests
  • PUT requests
  • PATCH requests
  • DELETE requests

3. Installing Axios

Axios can be installed using npm.

npm install axios

After installation, Axios can be imported into React components.

4. Importing Axios

Import Axios into your React component using:

import axios from "axios";

You can then use the Axios methods to make HTTP requests.

5. Axios GET Request

The axios.get() method is used to retrieve data.

axios.get("/api/students")
    .then(response => {
        console.log(response.data);
    });

The response data is available through response.data.

6. Axios Response

An Axios response contains useful information about the HTTP request.

axios.get("/api/students")
    .then(response => {

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

    });

The data property contains the response body.

7. Axios with useEffect

In React, Axios is commonly used inside useEffect when data should be requested after rendering.

import {
    useEffect
} from "react";

import axios from "axios";

function Students() {

    useEffect(() => {

        axios.get("/api/students")
            .then(response => {
                console.log(response.data);
            });

    }, []);

    return <h2>Students</h2>;
}

8. Store Axios Data with useState

import {
    useEffect,
    useState
} from "react";

import axios from "axios";

function Students() {

    const [students, setStudents] = useState([]);

    useEffect(() => {

        axios.get("/api/students")
            .then(response => {
                setStudents(response.data);
            });

    }, []);

    return <h2>Students</h2>;
}

9. Display Axios Data

After storing the response data in state, you can display it in JSX.

{students.map(student => (
    <p key={student.id}>
        {student.name}
    </p>
))}

This example assumes the API returns an array of student objects.

10. Axios GET with async/await

Axios works well with the async/await syntax.

async function getStudents() {

    const response = await axios.get(
        "/api/students"
    );

    console.log(response.data);
}

11. Async Function Inside useEffect

An asynchronous function can be created inside the effect and then called.

useEffect(() => {

    async function loadStudents() {

        const response = await axios.get(
            "/api/students"
        );

        setStudents(response.data);
    }

    loadStudents();

}, []);

12. Axios POST Request

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

axios.post("/api/students", {
    name: "Rahul",
    course: "React"
})
.then(response => {
    console.log(response.data);
});

13. POST Request with Form Data

Form values can be sent to an API using Axios.

const student = {
    name: "Amit",
    email: "amit@example.com",
    course: "React"
};

axios.post(
    "/api/students",
    student
)
.then(response => {
    console.log(response.data);
});

14. Axios PUT Request

The axios.put() method can be used to update a resource.

axios.put("/api/students/101", {
    name: "Rahul Kumar",
    course: "React"
})
.then(response => {
    console.log(response.data);
});

15. Axios PATCH Request

The axios.patch() method can be used when you want to update specific parts of a resource.

axios.patch("/api/students/101", {
    course: "Advanced React"
})
.then(response => {
    console.log(response.data);
});

16. Axios DELETE Request

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

axios.delete("/api/students/101")
    .then(response => {
        console.log(response.data);
    });

17. Handling Axios Errors

Axios requests can be handled with catch().

axios.get("/api/students")
    .then(response => {
        setStudents(response.data);
    })
    .catch(error => {
        console.log(error);
    });

18. Error State with Axios

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

useEffect(() => {

    axios.get("/api/students")
        .then(response => {
            setStudents(response.data);
        })
        .catch(error => {
            setError(error.message);
        });

}, []);

The error message can then be displayed in the UI.

19. Loading State with Axios

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

useEffect(() => {

    axios.get("/api/students")
        .then(response => {
            setStudents(response.data);
        })
        .finally(() => {
            setLoading(false);
        });

}, []);

The finally() block can run after the request completes, regardless of whether it succeeds or fails.

20. Display Loading and Error Messages

if (loading) {
    return <p>Loading...</p>;
}

if (error) {
    return <p>Error: {error}</p>;
}

This provides feedback to users while API data is being loaded or when a request fails.

21. Axios Request with Route Parameter

Axios can work with route parameters to retrieve a specific resource.

const { id } = useParams();

useEffect(() => {

    axios.get(`/api/students/${id}`)
        .then(response => {
            setStudent(response.data);
        });

}, [id]);

22. Axios Request Configuration

Axios requests can receive configuration options.

axios.get("/api/students", {
    headers: {
        Authorization: "Bearer TOKEN"
    }
})
.then(response => {
    console.log(response.data);
});

Configuration can include headers, parameters, timeout settings, and other request options.

23. Query Parameters

Axios can send query parameters using the params option.

axios.get("/api/students", {
    params: {
        course: "React",
        page: 1
    }
})
.then(response => {
    console.log(response.data);
});

This can result in a request containing query parameters such as ?course=React&page=1.

24. Axios Instance

For larger applications, an Axios instance can be created with common configuration.

import axios from "axios";

const api = axios.create({
    baseURL: "/api"
});

export default api;

The instance can then be reused for API requests.

25. Using an Axios Instance

import api from "./api";

api.get("/students")
    .then(response => {
        console.log(response.data);
    });

The baseURL configured in the instance is automatically used.

26. Axios Interceptors

Axios supports interceptors that can process requests or responses before they are handled by application code.

api.interceptors.request.use(
    config => {

        return config;
    }
);

Interceptors can be useful for common request or response handling.

27. Axios and Forms

Axios can be used to submit React form data to a backend API.

async function handleSubmit(e) {

    e.preventDefault();

    await axios.post(
        "/api/students",
        formData
    );
}

This pattern is commonly used for registration, admission, contact, and other forms.

28. Axios API Workflow

A common React Axios workflow is:

React Component
       ↓
Axios Request
       ↓
API
       ↓
Server
       ↓
Axios Response
       ↓
setState()
       ↓
Updated UI

29. Complete Axios Example

import {
    useEffect,
    useState
} from "react";

import axios from "axios";

function Students() {

    const [students, setStudents] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState("");

    useEffect(() => {

        async function loadStudents() {

            try {

                const response = await axios.get(
                    "/api/students"
                );

                setStudents(response.data);

            } catch (err) {

                setError(
                    err.message
                );

            } finally {

                setLoading(false);

            }
        }

        loadStudents();

    }, []);

    if (loading) {
        return (
            <h3>
                Loading students...
            </h3>
        );
    }

    if (error) {
        return (
            <h3>
                Error: {error}
            </h3>
        );
    }

    return (
        <div>

            <h2>
                Student List
            </h2>

            {students.map(student => (

                <div
                    key={student.id}
                    className="card mt-3"
                >

                    <div className="card-body">

                        <h4>
                            {student.name}
                        </h4>

                        <p>
                            Course: {student.course}
                        </p>

                    </div>

                </div>

            ))}

        </div>
    );
}

export default Students;

30. Axios Best Practices

  • Install Axios before importing it.
  • Keep API requests organized.
  • Use useEffect for appropriate data-fetching effects.
  • Use useState for data that affects the UI.
  • Handle loading and error states.
  • Use async/await when it improves readability.
  • Use Axios instances for shared configuration in larger applications.
  • Keep API URLs and configuration easy to maintain.
  • Use query parameters when appropriate.
  • Do not expose sensitive credentials in client-side code.
Axios
  ↓
Request
  ↓
API
  ↓
Response
  ↓
State
  ↓
UI

📌 Key Points

  • Axios is a Promise-based HTTP client.
  • Install Axios using npm install axios.
  • Use axios.get() to retrieve data.
  • Use axios.post() to send data.
  • Use axios.put() or axios.patch() to update data.
  • Use axios.delete() to delete a resource.
  • Axios response data is available through response.data.
  • Axios can be used with useEffect and useState.
  • Loading and error states should be handled appropriately.
  • Axios instances can help organize larger API-based applications.

🧠 Quick Quiz

Question: Which command is used to install Axios in a React project?