Simon
Simon

Reputation: 492

How to update array element using setState in React?

If I had an array structure similar to this:

person[{id: 0, firstname: 'john', surname: 'smith'}, 
       {id: 1, firstname: 'jane', surname: 'smith'}]

Then using an event handler to catch some change and using setState, how could I update the array element similar to this:

handleChangeEvent(newSurname, id){
     this.setState({ person[id].surname : newSurname})
}

Upvotes: 1

Views: 227

Answers (3)

Nathan
Nathan

Reputation: 8151

Perhaps you could try something along the lines of:

handleChangeEvent(newSurname, id){
  this.setState(prevState => ({
    people: prevState.people.map(
      person => person.id === id ? { ...person, surname: newSurname } : person
    )
  }));
}

In this code snippet we are getting a reference to your people array in your component's state. Then we are filtering this array based on ids and if the id matches the person whose name needs to be updated we set the surname appropriately. Otherwise, we just return the existing object if the id doesn't match the person who needs to be updated.

Hopefully that helps!

Upvotes: 0

Patrick Roberts
Patrick Roberts

Reputation: 51876

Use setState()'s updater callback to perform your state change in a single atomic operation without the risk of overwriting (or being overwritten by) other state changes to the component in the same event tick:

handleChangeEvent(surname, id) {
    this.setState(({ people }) => ({
        people: people.map(
            person => person.id === id ? { ...person, surname } : person
        )
    }));
}

Upvotes: 2

Ajay Ullal
Ajay Ullal

Reputation: 378

This is basically what you are looking for. I'd however recommend you to use a library like immer to create immutable objects.

handleChangeEvent(newSurname, id){
     this.setState({
                     people : Array.from(this.state.people, person => {
                          if(person[id] === id)
                           return {...person, surname: newSurname}
                          return person
                     })   
     })
}

Upvotes: 0

Related Questions