adding same item with unique index to state array on click

Viewed 35

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.

1 Answers

You can do this by always picking the last index property of the last element. Example:

const arr = [{index: 1, val: "a"}];
document.querySelector('button').addEventListener('click', function(){
  arr.push({index: arr[arr.length - 1].index + 1, val: "a"});
  console.log(arr);
});
<button>increment + </button>

Related