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

1

3 Answers 3

3

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});
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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 });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.