Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching data using useEffect() make get requests each miliseconds

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]);
like image 487
Mustafa Mengütay Avatar asked Aug 03 '26 16:08

Mustafa Mengütay


1 Answers

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!

like image 59
Harsh nahta Avatar answered Aug 05 '26 05:08

Harsh nahta