Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

111
Visualizações
Does this two useEffects makes a long loop?

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])
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

  • 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(() => { ... }, []);

about 4 years ago · Juan Pablo Isaza Relatório

0

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])
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda