Accepted answer

while updating state the key part is to treat it as if it is immutable. any solution would work fine if you can guarantee it.

here is my solution using immutability-helper:


  var update = require('immutability-helper');

  handlecommentedit: function(id, text) {
    var data =;
    var commentindex = data.findindex(function(c) { 
        return == id; 

    var updatedcomment = update(data[commentindex], {text: {$set: text}}); 
    var newdata = update(data, {
        $splice: [[commentindex, 1, updatedcomment]]
    this.setstate({data: newdata});

following questions about state arrays may also help:


you can do this with multiple way, i am going to show you that i mostly used. when i am working with arrays in react usually i pass a custom attribute with current index value, in the example below i have passed data-index attribute, data- is html 5 convention.


//handlechange method.
  const {name, value} = e,
        index ='data-index'), //custom attribute value
        updatedobj = object.assign({}, this.state.arr[i],{[name]: value});
  //update state value.
    arr: [
      ...this.state.arr.slice(0, index),
      ...this.state.arr.slice(index + 1)


trying to clean up/ explain better how to do this and what's going on.

  • first, find the index of the element you're replacing in the state array.
  • second, update the element at that index
  • third, call setstate with the new collection
import update from 'immutability-helper';

// this.state = { employees: [{id: 1, name: 'obama'}, {id: 2, name: 'trump'}] } 

updateemployee(employee) {
    const index = this.state.employees.findindex((emp) => ===;
    const updatedemployees = update(this.state.employees, {$splice: [[index, 1, employee]]});  // array.splice(start, deletecount, item1)
    this.setstate({employees: updatedemployees});

edit: there's a much better way to do this w/o a 3rd party library

const index = this.state.employees.findindex(emp => ===;
employees = [...this.state.employees]; // important to create a copy, otherwise you'll modify state outside of setstate call
employees[index] = employee;


i quite like doing this with object.assign rather than the immutability helpers.

handlecommentedit: function(id, text) {
      data: => ( === 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

  data: => ( === id ? {...el, text} : el))

Related Query

More Query from same tag