1

I have a state object called items.

items: [
    {
      name: 'John'
      id: '1',
      checked: false,
    },
    {
      name: 'Dude'
      id: '2',
      checked: true,
    }
]

On UI Click i need to update checked property to true of item with id = 1 How do i use the setState for the items for updating one(single) item in the items

Peekay
  • 441
  • 3
  • 10
  • 25
  • Possible duplicate of [Whats the best way to update an object in an array in ReactJS?](https://stackoverflow.com/questions/28121272/whats-the-best-way-to-update-an-object-in-an-array-in-reactjs) – nahuelhds May 14 '19 at 18:25

3 Answers3

2

Something like this? Explanation in the comments:

onClick(id) {
  // Create a temporary copy of your items array
  const itemsCopy = this.state.items.slice();

  // Find the index of the items where the item has the id you want
  const idx= itemsCopy.findIndex(x => x.id === id);

  // Re-assign the item to have the same values as before (name and id), but change the checked to true
  itemsCopy[idx] = {...itemsCopy[idx], checked: true};

  // Update the state with our modified copy
  this.setState({items: itemsCopy});
}
Chris
  • 57,622
  • 19
  • 111
  • 137
1
const {items} = this.state;
const index = items.findIndex(val=>val.id ===1);
items[index].checked = true;
this.setState({items});
Omer Khan
  • 437
  • 2
  • 8
1

The 'items' object in state should be updated. So slice can be used to copy array. And it should be enough to set it back to state, so component will understand that state is changed.

let items = this.state.items.slice();

const index = items.findIndex(val => val.id === 1);
items[index].checked = true;
this.setState({ items });