DEV Community

ManikandanH
ManikandanH

Posted on

React Updating Array SetState Callback in for loop using Push

Having an issue in react state updating in an array, and also found the solution the problem is i need to know the cause of the issue.

constructor() {
super();`
this.state = {
name: "",
exampleArray: [],
nameArr: ["s", "s1", "s2", "s3", "s4"]
};
}

componentDidMount() {
for (let i = 0; i < 5; i++) {
this.setState({
name: "Manikandan",
exampleArray: [
...this.state.exampleArray,
this.state.exampleArray.push(this.state.nameArr[i])
]
});
}
In the above code am maintaining a state array called nameArr and looping this array in didMount LifeCycle and changing the state of exampleArray by pushing into this i know setstate is async and react will batch these and will render the component only once, but the problem is the result array am getting for the exampleArray is exampleArray = ['s','s1','s2','s3',5] However i solved this issue using setState via Callback without using array.push, simply appending the array in newly created reference by using spread operator.

But i want to know why particularly the last element of the loop is pushing the length of the array instead of the value when using normal setState.

Please see the below code for full reference

class App extends Component {
constructor() {
super()
this.state = {
name: "",
exampleArray: [],
nameArr: ["s", "s1", "s2", "s3", "s4"],
}
}

componentDidMount() {

for (let i = 0; i < 5; i++) {
  this.setState({
    name: "Manikandan",
    exampleArray: [
      ...this.state.exampleArray,
      this.state.exampleArray.push(this.state.nameArr[i]),
    ],
  })
} //LOGS: exampleArray: ['s','s1','s2','s3', 5]

for (let i = 0; i < 5; i++) {
  this.setState((prevState) => {
    return {
      name: prevState.name + "Manikandan",
      exampleArray: [
        ...prevState.exampleArray,
        prevState.exampleArray.push(prevState.nameArr[i]),
      ],
    }
  })
} //LOGS: exampleArray: [1,2,3,4,5]

for (let i = 0; i < 5; i++) {
  this.setState((prevState) => {
    return {
      name: prevState.name + "Manikandan",
      exampleArray: [...prevState.exampleArray, prevState.nameArr[i]],
    }
  })
} //LOGS: exampleArray: ['s','s1','s2','s3','s4'] ----> Expected Result

}
}

Top comments (0)