Imagine you are browsing the product page for a Nike T-shirt. You select black color and size S, adding it to your cart. The cart now shows 1 Nike T-SHIRT with attributes color: black, size: S. However, if you then switch to white color and size M on the same page, the previously added shirt's attributes change to color: white and size: M. So now the cart has 2 T-SHIRTS with size: M and color: black. Where am I going wrong?
class PDP extends Component {
state = {
currentProduct: this.props.location.state,
selectState: [],
testObj: {},
}
render() {
let product = this.state.currentProduct;
let handleChange = (evt,attribute) => {
const test = Object.assign({}, product);
this.state.testObj[attribute] = evt.target.value;
this.state.selectState.push(this.state.testObj);
let selectedAttributes = [...new Set(this.state.selectState)];
test.selectedAttributes = selectedAttributes;
this.setState((state) => ({
currentProduct: test
}))
}
<button className="addToCart" onClick={() => this.props.data.addProduct(this.state.currentProduct)}>ADD TO CART</button>
addProduct = (product) => {
this.setState((state) => ({
cart: state.cart.concat(product),
}))
}