Reputation: 73
I am getting the value of id and quantity during the click button. I want add a new array inside the object array. Below is the code
adddata =(d,v) => {
const product = [];
for (let i = 0; i < 1; i++) {
product.push({
product_id:d,
cart_quantity:v
});
}
console.log(product);
<button value={this.state.quantity} className="btn" onClick={adddata} data-id={item.product_id}>Add to cart</button>
The only issue with this implementation is that. it replacing the new value with an existing one. I want to merge it dynamically every time click on the button.
Please help
Upvotes: 0
Views: 3153
Reputation: 6359
You defined the variable product
inside the function, So each time when you execute the function, It will be reinitialized.
Use Global Variable / State
// global
const product = [];
addData =(d,v) => {
// I removed the loop because it's useless here.
product.push({
product_id:d,
cart_quantity:v
});
}
Upvotes: 1