Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!