I am working on a problem where an state array items is blank and needs to be added with an object item on click of a button
newItem={index:0,val:"a"}; items=[newItem1,newItem2]; so expected outcome is items:[{index:0,val:"a"},{index:1,val:"a"}]
I wrote code:
state:{
items:[],
counter:0,
}
const newItem={index:0,val:"a"};
onclick=()=>
{
newItem.index=this.state.counter;
this.setState(prevState => ({items:[...prevState.items,newItem]}),()=>{console.log(this.state.rowData);});
this.setState({counter:this.state.counter+1});
}
However it is returning me
items:[{index:1,val:"a"},{index:1,val:"a"}] and on each click index of all array items get updated. I tried concat, push, all are updating index for both array elements.