I am fetching a data from an API and setting a state. When I do that process, It makes get requests each millisecond. This problem happens, if I set the dependencies array. I want to make a request when API is updated.
const [products, setProducts] = useState({ baskets: [] });
useEffect(() => {
fetch("/api")
.then((response) => response.json())
.then((products) => {
setProducts(products);
});
}, [products]);
Remove the dependency from the useEffect Hook
useEffect(() => {
fetch("/api")
.then((response) => response.json())
.then((products) => {
setProducts(products);
});
}, []);
Here you are updating results into setProducts and it triggers products state change due to useEffect behaviour, So it'll be called infinety. Also I suggest you to change
.then((result) =>{
setProducts(result);
})
Here, you'll face issues with scope in products.
So your final could should be this :
useEffect(() => {
fetch("/api")
.then((response) => response.json())
.then((result) => {
setProducts(result);
});
}, []);
Also As per your below comment, here is the updated sample code with use of useCallback
const [products, setProducts] = useState({ baskets: [] });
const fetchProdcuts = useCallback(() => {
fetch("/api")
.then((response) => response.json())
.then((result) => {
setProducts(result);
});
}, []);
useEffect(() => {
fetchProdcuts();
}, [fetchProdcuts]);
** call fetchProdcuts method whenever you need to refresh the product lists**
Hope it helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With