Whats the best way to update an object in an array in ReactJS?

I quite like doing this with Object.assign rather than the immutability helpers.

handleCommentEdit: function(id, text) {
    this.setState({
      data: this.state.data.map(el => (el.id === id ? Object.assign({}, el, { text }) : el))
    });
}

I just think this is much more succinct than splice and doesn’t require knowing an index or explicitly handling the not found case.

If you are feeling all ES2018, you can also do this with spread instead of Object.assign

this.setState({
  data: this.state.data.map(el => (el.id === id ? {...el, text} : el))
});

Leave a Comment