Here is, my code. i want to add a spinner when data is loading then after finish loading display the data.
{/* product section */}
<section className="container mx-auto my-5 row">
<h6 className="text-center">WANT TO SEE</h6>
<h2 className="text-center mb-5">Our Services</h2>
{
Products.slice(0,6)?.map((product) => {
return <Product key={product._id} product={product}></Product>;
})
}
</section>
And This is the custom hook
import { useEffect, useState } from "react";
const LoadProducts = () => {
const [Products, setProducts] = useState([]);
useEffect(()=>{
fetch('http://localhost:8080/products')
.then(res=>res.json())
.then(data=>setProducts(data))
},[]);
return [Products, setProducts]
}
export default LoadProducts;
2
Answers
Try this:
Note the custom hook now returns [Products, setProducts, loading].
Now you can add some conditional code to your JSX that shows a loading spinner while loading is true
I would do something like this but you can customize it to your needs. The trick is really to create a loading state which initially will be false. When you start calling your api, you will set your loading to true. Once you either get a response or fail you set it to false.