Lesson 30 — Axios in React (API Calls Made Easy)

🧭 Introduction

In the previous lesson, you learned how to call APIs using the Fetch API. While Fetch works well, handling real-world requirements like:

  • Automatic JSON conversion
  • Better error handling
  • Request & response interceptors
  • Cleaner syntax

can become difficult.

To solve this, developers commonly use Axios, a popular JavaScript library for making HTTP requests.

In this lesson, you will learn:

  • What Axios is
  • Why Axios is preferred over Fetch
  • How to use Axios in React
  • Handling loading & errors
  • GET and POST requests
  • Best practices

❓ What is Axios?

Axios is a promise-based HTTP client used to:

Make API requests easily from the browser or Node.js.

Axios automatically:

  • Converts response to JSON
  • Handles errors better than Fetch
  • Supports request/response interceptors

🧠 Why Use Axios in React?

❌ Limitations of Fetch API

  • Manual JSON parsing
  • Error handling is not automatic
  • More boilerplate code

✅ Benefits of Axios

✔ Cleaner syntax
✔ Automatic JSON response
✔ Better error handling
✔ Supports interceptors
✔ Widely used in production


🔄 Fetch vs Axios (Quick Comparison)

FeatureFetch APIAxios
Built-in✅ Yes❌ No
JSON handlingManualAutomatic
Error handlingManualBetter
Interceptors
Request cancel

📦 Step 1: Install Axios

npm install axios


🧠 Basic Axios Syntax

axios.get("https://api.example.com/data")
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

👉 Axios response data is available via response.data


🧪 Simple Example: GET Request in React


📄 Users.jsx

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

const Users = () => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    axios
      .get("https://jsonplaceholder.typicode.com/users")
      .then((response) => {
        setUsers(response.data);
      });
  }, []);

  return (
    <div>
      <h2>User List</h2>
      <ul>
        {users.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default Users;


⏳ Handling Loading State with Axios

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

useEffect(() => {
  axios
    .get("https://jsonplaceholder.typicode.com/users")
    .then(res => setUsers(res.data))
    .finally(() => setLoading(false));
}, []);

if (loading) return &lt;p>Loading...&lt;/p>;


❌ Handling Errors with Axios

Axios throws an error automatically for:

  • Network errors
  • 4xx / 5xx responses

✅ Error Handling Example

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

useEffect(() => {
  axios
    .get("https://jsonplaceholder.typicode.com/users")
    .then(res => setUsers(res.data))
    .catch(err => setError(err.message));
}, []);

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


🧩 Complete Axios Example (Best Practice)

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

const Users = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    axios
      .get("https://jsonplaceholder.typicode.com/users")
      .then(res => setUsers(res.data))
      .catch(err => setError(err.message))
      .finally(() => setLoading(false));
  }, []);

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

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
};

export default Users;


📤 POST Request with Axios

axios.post("https://jsonplaceholder.typicode.com/posts", {
  title: "Axios Example",
  body: "Learning Axios in React",
})
.then(res => console.log(res.data));


🔧 Axios Global Configuration (Important)

Create Axios Instance

import axios from "axios";

const api = axios.create({
  baseURL: "https://api.example.com",
  headers: {
    "Content-Type": "application/json",
  },
});

export default api;


🔐 Axios Interceptors (Preview)

api.interceptors.request.use(config => {
  console.log("Request sent");
  return config;
});

👉 Interceptors are useful for auth tokens (covered later).


⚠ Common Mistakes

❌ Not handling errors
❌ Making API calls without useEffect
❌ Hardcoding URLs everywhere
❌ Not using Axios instance


🎯 Best Practices

✅ Create reusable Axios instance
✅ Handle loading & error state
✅ Keep API logic clean
✅ Use environment variables for base URLs


❓ FAQs — Axios in React

🔹 Is Axios better than Fetch?

Axios is preferred for real-world applications due to cleaner syntax and features.


🔹 Can Axios replace Fetch completely?

Yes. Many projects use Axios exclusively.


🔹 Is Axios safe?

Yes. It is widely used and maintained.


🔹 Should I use Axios in small apps?

Fetch is enough for small apps. Axios shines in medium/large apps.


🧠 Quick Recap

✔ Axios simplifies API calls
✔ Automatic JSON handling
✔ Better error handling
✔ Widely used in production


🎉 Conclusion

Axios makes API integration in React cleaner, more readable, and more powerful. Mastering Axios prepares you for real-world backend communication, authentication, and scalable applications.


👉 Next Lesson (SECTION 6):
Lesson 31 — Handling Loading & Errors

Leave a Comment