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

163
Visualizações
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 Respostas
Responde à pergunta

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 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