I am working on a problem where an state array items:[{index:0,val:"a"}] needs to be appended with new index and same value like
items:[{index:0,val:"a"},{index:1,val:"a"}] on click of button.
I wrote code:
state:{
items:[],
counter:0,
}
const newItem={index:0,val:"a"};
on click
{
newItem.index=this.state.rowCounter;
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.