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);
CodePudding user response:
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.