0

Trying to avoid a duplicate question but I think this varies from the previous ones I searched for.
I have a state of 'favorites' that is an array of items. I want to add an item to the array in the following function. I'm creating a variable that has the value of the favorites, then pushing the new value into that variable of arrays and setting the favorite state to the new variable.

This is working for me but I am trying to see if it's an improper way to do it.

  handleAddFavorite(item) {
    let favorites = this.state.favorites;
    favorites.push(item);

    this.setState({
      favorites: favorites
    });
  }
  • https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-reactjs – Yossi Jun 24 '18 at 06:37
  • You should use **immutability-helper**. https://github.com/kolodny/immutability-helper/blob/master/README.md – yeshashah Jun 24 '18 at 06:44
  • Possible duplicate of [Correct modification of state arrays in ReactJS](https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-reactjs) – yeshashah Jun 24 '18 at 06:46
  • If you consider that you are setting `favourites` by reference, it becomes a reference to favourites in the state. By using `Array.push` you are then mutating (by reference) the original state member. So yes, it's bad practice. – Tim Ogilvy Jun 24 '18 at 06:51
  • I'm very surprised your component rerenders when you do it in this manner. React checks for difference by reference. If you mutate the array, it's still the same reference and would not pick up that it should render new content – Andrew Jun 24 '18 at 08:55

3 Answers3

0

To pushing item into state array you can use ES6 spread syntax like this:

this.setState({
  favorites: [...this.state.favorites, item]
});
Soroush Chehresa
  • 5,490
  • 1
  • 14
  • 29
0

You are referencing the array and not creating a new one.

One way to create a new array, is using the ES2015 array spread:

 handleAddFavorite(item) {
    const {favorites} = this.state;

    this.setState({
      favorites: [...favorites, item]
    });
  }
Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99
0

Here you can not push the object to a state array like this. You can push like your way in a normal array. Here you have to set the state,

this.setState({ 
     favorites: [...this.state.favorites, item] 
})
Sachin Muthumala
  • 775
  • 1
  • 9
  • 17