For some reason, the loading state doesn't change when I'm using this method to fetch from the API.
How to display "Loading..." while the call is running.
- async-await doesn't work either, that's why I'm using this method to fetch.
const [product, setProduct] = useState({});
const [loading, setLoading] = useState(false);
const productId = 1;
const fetchProduct = () => {
setLoading(true);
//here commerce is my api, so i fetched the product details and set it to the product state
commerce.products.retrieve(productId).then(data => setProduct(data));
setLoading(false);
}
useEffect(() => {
fetchProduct();
})
if (loading) {
return (
<span>Loading...</span>
)
}
return (
<h1>{product.name}</h1>
)
useEffect()without second argument (dependencies) will trigger after each render. Make sure to pass an empty array if you only want to fire a request on component mount without making requests thereafter. eg.useEffect(() => { code... }, [])