DEV Community

Cover image for 🔄 How to Fetch and Display API Data in React Using Axios
Manu Kumar Pal
Manu Kumar Pal

Posted on

🔄 How to Fetch and Display API Data in React Using Axios

Hey DEV community! 👋 you’ll learn step by step how to fetch data from an API and display it in your React app using Axios — one of the most popular libraries for making HTTP requests.

Let’s get started! 🚀

1️⃣ Install Axios
First, install Axios in your React project:

npm install axios
Enter fullscreen mode Exit fullscreen mode

2️⃣ Import Axios in Your Component
At the top of your React component file, import Axios:

import axios from "axios";
Enter fullscreen mode Exit fullscreen mode

3️⃣ Create State to Store API Data 🗃️
Use React’s useState hook to store the fetched data:

import { useState, useEffect } from "react";
Enter fullscreen mode Exit fullscreen mode
function DataFetcher() {
  const [data, setData] = useState([]);
Enter fullscreen mode Exit fullscreen mode

4️⃣ Fetch Data with Axios Inside useEffect
Use useEffect to fetch data when the component mounts:

 useEffect(() => {
    axios
      .get("https://jsonplaceholder.typicode.com/posts") // replace with your API URL
      .then((response) => {
        setData(response.data); // save API response data
      })
      .catch((error) => {
        console.error("Error fetching data:", error);
      });
  }, []);
Enter fullscreen mode Exit fullscreen mode

5️⃣ Display API Data in JSX 📄
Render the fetched data in your component:

 return (
    <div className="p-4">
      <h1 className="text-2xl font-bold mb-4">Fetched Posts 📬</h1>
      <ul className="space-y-2">
        {data.map((item) => (
          <li key={item.id} className="border p-2 rounded">
            <h2 className="font-semibold">{item.title}</h2>
            <p>{item.body}</p>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default DataFetcher;
Enter fullscreen mode Exit fullscreen mode

🎉 That’s it!
You’ve learned how to fetch and display API data in React with Axios. Now you can integrate any API into your React app. Happy coding! 💻

Top comments (0)