Ahmad Ali
Ahmad Ali

Reputation: 774

useEffect running infinite loop, although it supposed to work once

I have this effect which supposed to work once, but it is going infinite loop. can we get an explanation of what's happening?


   useEffect(() => {
     (async () => {
       const cartId = localStorage.getItem('cart-id');
       try {
         const {cart, products} = await (await fetch('/api/cart' + (cartId ? '?id=' + cartId : ''))).json();
         setCart(cart);
         setProducts(products);
       } catch (e) {}
     })();
   }, []);

I have the cart-id successfully.

try-catch supposed to work once, even if I don't get any products for any reason?

Upvotes: 1

Views: 47

Answers (1)

Andrei
Andrei

Reputation: 12036

2nd parameter (empty array in your example) allows to run your code, only if the params changed. to make use of that try make your effect dependant on cartId


  const cartId = localStorage.getItem('cart-id');
  useEffect(() => (async () => {
       try {
         const {cart, products} = await (await fetch('/api/cart' + (cartId ? '?id=' + cartId : ''))).json();
         setCart(cart);
         setProducts(products);
       } catch (e) {}
     })(), [cartId]);

Upvotes: 1

Related Questions