I want to add spinner while loading data from database. For fetching data I am using react-hook. Here is my code ,how can I add spinner here?
import React from "react";
import { useNavigate } from "react-router-dom";
import useInventories from "../../../hooks/useInventories";
import Inventory from "../Inventory/Inventory";
const Inventories = () => {
const [inventories] = useInventories();
return (
<>
<div id="inventory" className="container mt-5 ">
<h2 className="text-center my-5 text-primary ">Inventory</h2>
<div className="row row-cols-1 row-cols-md-3 g-4 border-1 ">
{inventories.slice(0, 6).map((inventory) => (
<Inventory key={inventory._id} inventory={inventory}></Inventory>
))}
</div>
</div>
</>
);
};
export default Inventories;
It take a little bit time to load data from mongodb. So I want to add spinner loading before that.
CodePudding user response:
You can do solution with useEffect. Basically initial loading is true and it becomes false when you have inventories data. I also see that you are using tailwind so you can set spinner icon animation directly with animate-spin
import React from "react";
import { useNavigate } from "react-router-dom";
import useInventories from "../../../hooks/useInventories";
import Inventory from "../Inventory/Inventory";
const Inventories = () => {
const [inventories] = useInventories();
const [loading, setLoading] = useState(true)
useEffect(() => {
if(inventories?.length > 0) {
setLoading(false)
}
}, [inventories])
return (
<>
{loading <SpinnerComponent/> }
{!loading
<div id="inventory" className="container mt-5 ">
<h2 className="text-center my-5 text-primary ">Inventory</h2>
<div className="row row-cols-1 row-cols-md-3 g-4 border-1 ">
{inventories.slice(0, 6).map((inventory) => (
<Inventory key={inventory._id} inventory={inventory}></Inventory>
))}
</div>
</div>}
</>
);
};
export default Inventories;