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
2️⃣ Import Axios in Your Component
At the top of your React component file, import Axios:
import axios from "axios";
3️⃣ Create State to Store API Data 🗃️
Use React’s useState hook to store the fetched data:
import { useState, useEffect } from "react";
function DataFetcher() {
const [data, setData] = useState([]);
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);
});
}, []);
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;
🎉 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)