Calling API or fetching data from backend API in reactjs
Hi there , in this article I am going to show, how call API from react component or fetching data from backend API using react hook and axios library
Very first need to install axios using NPM command like bellow
npm i axios
Then import useState, useEffect hook from react, axios from axios and start working
Code Example
import React, { useEffect, useState } from "react";
import axios from "axios";
export default function App() {
const [products, setProducts] = useState([]);
const [err, setErr] = useState();
const getData = async () => {
try {
const { data } = await axios.get(`Put your API end point here`);
{
/*You can use this fack API end point for testing `https://fakestoreapi.com/products` */
}
setProducts(data);
} catch (error) {
setErr(error.message);
}
};
useEffect(() => {
getData();
}, []);
return (
<>
<p>{err ? err : null}</p>
<div>
{products ? (
products.map((product) => {
return (
<div key={product.id}>
<h1>{product.title}</h1>
<p>{product.description}</p>
</div>
);
})
) : (
<p>Data is loadin...</p>
)}
</div>
</>
);
}