Does this two useEffects makes a long loop?

Viewed 29

I am writing a React app. I used two useEffects. One useEffects gets data from firebase and changes "cartItems" and "totalAmount".

The second useEffect has these two dependencies and it runs when these dependencies change and overwrites data model.

I think it makes loop with no point (I might be wrong). How can I solve it and make it efficient? I would like to transform to Redux Toolkit Actions, but first I would like to do it in vanilla React.

useEffect(() => {
    fetch('https://italianhouse-1aef0-default-rtdb.europe-west1.firebasedatabase.app/cart.json')
    .then(res => res.json())
    .then(data => {
      console.log(data)
      const keys = Object.keys(data.cartItems)
      keys.forEach(key => dispatch(cartActions.getCartData(data.cartItems[key])))
      dispatch(cartActions.setFetchedTotalAmount(data.totalAmount))
      
    })
  }, [dispatch])

  useEffect(() => {
    fetch('https://italianhouse-1aef0-default-rtdb.europe-west1.firebasedatabase.app/cart.json', {
            method: 'PUT',
            body: JSON.stringify({cartItems: cartItems, totalAmount: totalAmount}),
            headers: {
                'content-type': 'application/json'
            }

        })
  }, [cartItems, totalAmount])
2 Answers
  • Looks like your first useEffect pushing you in the loop.

  • Passing an empty array as the second argument to useEffect, which makes it only run on the mount and unmount.

    useEffect(() => { ... }, []);

I have solved it by using additional boolean

let isInitial = true

useEffect(() => {
    fetch('https://italianhouse-1aef0-default-rtdb.europe-west1.firebasedatabase.app/cart.json')
    .then(res => res.json())
    .then(data => {
      const keys = Object.keys(data.cartItems)
      keys.forEach(key => loadedMeals.push(data.cartItems[key]) )
      dispatch(cartActions.replaceCart(loadedMeals))
      dispatch(cartActions.setFetchedTotalAmount(data.totalAmount))
      isInitial = false
    })
  }, [dispatch])
  
  useEffect(() => {
    if (isInitial) return
    
    fetch('https://italianhouse-1aef0-default-rtdb.europe-west1.firebasedatabase.app/cart.json', {
            method: 'PUT',
            body: JSON.stringify({cartItems: cartItems, totalAmount: totalAmount}),
            headers: {
                'content-type': 'application/json'
            }

        })
        
  }, [cartItems, totalAmount])
Related