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

123
Visualizações
using state from a context provider within my useEffect dependency array causes an infinite loop

I am using the shopify-buy SDK, which allows me to retrieve the current cart of the user. I am trying to store that cart in my CartProvider which is then used in my Cart component. The problem is when I retrieve information from the cart it's acting a little slow so my component needs to be updated when the state changes, currently I have the following in my getShopifyCart function which is located in my CartProvider.

const [cartItems, setCartItems] = useState([])

const getShopifyCart = () => {
    return client.checkout
      .fetch(currentVendor.cartId)
      .then((res) => {
        const lineItemsData = res.lineItems.map((item) => {
          return {
            title: item.title,
            quantity: item.quantity,
          }
        })
        setCartItems(lineItemsData)
        setLoading(false)
      })
      .catch((err) => console.log(err))
  }

In my Cart component I have the following useEffect.

useEffect(() => {
    getShopifyCart()
  }, [cartItems])

But this causes an infinite loop, even though the cartItems state isn't changing.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are setting the state cartItems inside getShopifyCart which you are calling inside a useEffect which has cartItems as a dependency. Even though the content of the data has not changed, you are creating a new object, hence its hash has changed as well which causes the useEffect to be called again.

If you want to initially fetch the data and set the state, then you need to pass an empty dependency array.

useEffect(() => {
   getShopifyCart()
}, [])
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