Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an object with setState() to an array of objects

My component's state is an array of objects:

this.state = {
  userFavorites: [{id: 1, title: 'A'}, {id: 2, title: 'B'}]
}

I need to, everytime I click in a button, update my state with another object like the ones I have in my state above; for example: {id: 3, title: 'C'}.

If I simply concat them and set the state, the last object keeps being changed by the one that's being added.

Do I need the spread operator here?

like image 321
Rafael Guedes Avatar asked Mar 05 '23 05:03

Rafael Guedes


1 Answers

You should do it this way. Below is the most recommended way to push values or objects to an array in react

 this.setState( prevState => ({
     userFavorites: [...prevState.userFavourites,  {id: 3, title: 'C'}]
 }));

To push to the beginning of the array do it this way

   this.setState( prevState => ({
     userFavorites: [{id: 3, title: 'C'}, ...prevState.userFavourites]
  }));
like image 70
Hemadri Dasari Avatar answered Mar 20 '23 18:03

Hemadri Dasari