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

160
Vistas
The result fall into an infinite cycle in React.js

Could anyone help me to fix my issue? I'm a starter in React.js and I just made the component to show the cart results! but for some reason, it falls into an infinite cycle.

Issue screenshot: http://prntscr.com/1w5hbey

you can see the console data with this site URL. Thank you

https://side-cart-react.myshopify.com/products/test2

import React, { useState } from "react"
import ReactDom from "react-dom"

const LineItem = (props) => {
    return (
    <div className="line-item" data-line="">
      <div className="line-item__header">
        <div className="line-item__title">
          <p>{console.log(props.cart)}</p>
        </div>
        <p className="line-item__price"></p>
      </div>
    </div>
  )
}

const CartDrawer = () => {

    const [cart, setCart] = useState("");

    const getCart = () => {
        fetch("/cart.js", {
            method: 'GET',
            headers: new Headers({'content-type': 'application/json', 'X-Requested-With':'xmlhttprequest'})
        }).then(res => {
            return res.json();
        }).then(json => {
                setCart(json);
            console.log('state',cart);
        });
    }

    getCart();

    return  <LineItem cart={cart} />;
}

const root = document.getElementById('cart__drawer_items');

ReactDom.render(<CartDrawer />, root);
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

When you call setCart(json), it causes a rerender of your component. On this subsequent render, your function getCart() get called again, and thus you trap yourself inside an infinite loop. Instead, you should call getCart() within useEffect like this:

const CartDrawer = () => {
  useEffect(() => {
    getCart();
  }, []);

  return  ...;
}

This way, it will be called only once. If you want cart to update when some state or props change, you should add those variables into useEffect dependency array.

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