1

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})
}
2
  • Do you want it to add a new entry if the id doesn't exist and update an entry if the id does exist? Commented Dec 9, 2019 at 17:37
  • I'm looking at accomplishing this on the presumption that the ID does in fact exist Commented Dec 9, 2019 at 17:38

3 Answers 3

2

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

Comments

0

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

Comments

0

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!

2 Comments

Would be better to use the updater callback signature of setState() for atomicity since the new state is derived from the previous one. e.g. this.setState(prev => prev.map(person => ...))
Now your answer is no different than mine, other than syntax...

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.