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
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
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.