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)