Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update an object in an array of Objects using setState

I am using React, my state is defined as an array of object. I need to be able to change only one specific element in the state.data array, example object with id 1.

I would like to know:

  • what is the proper way how to use setState() in this scenario.

constructor(props) {
  super(props);
  this.state = {
    data: [{
        id: 0,
        title: 'Buy a',
        status: 0, // 0 = todo, 1 = done
      },
      {
        id: 1,
        title: 'Buy b',
        status: 0,
      },
      {
        id: 2,
        title: 'Buy c',
        status: 0,
      }
    ]
  };
  this.onTitleChange = this.onTitleChange.bind(this);
}
onTitleChange(id, title) {
  console.log(id, title);
  debugger
}
like image 811
Radex Avatar asked Aug 25 '17 09:08

Radex


People also ask

How do you update an object in an array of objects?

To update an object's property in an array of objects, use the map() method to iterate over the array. On each iteration, check if the current object is the one to be updated. If it is, modify the object and return the result, otherwise return the object as is. Copied!

How do you update list items in React?

To implement the change of item on click, we will create the list data as a state in react by using the useState hook. Then on onClick we will change the item. Step 3: Create folder components inside src folder of react project directory and inside the components folder create files List. jsx.


1 Answers

You can get do a cloning of the state object using spread operator and then find the index of object in array with a given id using findIndex method Modify the object and set the state.

constructor(props) {
  super(props);
  this.state = {
    data: [{
        id: 0,
        title: 'Buy a',
        status: 0, // 0 = todo, 1 = done
      },
      {
        id: 1,
        title: 'Buy b',
        status: 0,
      },
      {
        id: 2,
        title: 'Buy c',
        status: 0,
      }
    ]
  };
  this.onTitleChange = this.onTitleChange.bind(this);
}
onTitleChange(id, title) {
   var data = [...this.state.data];
   var index = data.findIndex(obj => obj.id === id);
   data[index].title = title;
   this.setState({data});
}
like image 144
Shubham Khatri Avatar answered Nov 13 '22 10:11

Shubham Khatri