I'm trying to add an object in the array defined in the state, which (object) I get from a child then moving up to the parent, setting it to parent's state and giving it to another(that child's code is down below) child as a prop. I saw some solutions but they are not working. The present solution gives me an infinite loop, props item is added over and over. So my question is how to add an item in the array which is defined in the state and the item that we are getting is a prop. Here's my code
import React, { Component } from "react";
import "./ShoppingCart.css";
class ShoppingCart extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
};
}
onAddItem = () => {
if(Object.keys(this.props.item).length !== 0)
//checking initial empty prop
{
const item = this.props.item;
//an object consist of {id,title,price...etc}
//the solution i found on the internet
const newList = this.state.items.concat(item);
console.log("New List",newList);
this.setState({
items:newList
})
}
};
render() {
this.onAddItem();
return (
<React.Fragment>
<button className="cart-button">
<img className="shopping-cart-img" src="./images/shopping-cart.png" />
{/* Here will be some code*/}
</button>
</React.Fragment>
);
}
}
export default ShoppingCart;
You are calling the function on every render and then setting state, causing another render, and then the render call the function again.... it's an infinite loop.
render() {
this.onAddItem(); // ❌ REMOVE THIS LINE
return (
<React.Fragment>
<button className="cart-button" onClick={this.onAddItem}> //✅ add onclick event to add item here
<img className="shopping-cart-img" src="./images/shopping-cart.png" />
{/* Here will be some code*/}
</button>
</React.Fragment>
);
Update constructor
constructor(props) {
super(props);
this.state = {
items: [],
};
this.onAddItem = this.onAddItem.bind(this)
}
Updated onAddItem
onAddItem = (item) => {
const newList = [...this.props.item, item]
this.setState({
items: newList
})
}
};