Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

124
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda