0

So, I have a a state of users which gets filled up with an array of Objects from the backend. Say, I want to update the details of a specific User Object from that array and then update the current state with the updated details. How do I go about doing that?

What I currently do is force a refetch from the server once the update request is successful to update the state again but I was wondering if there's a better way to do it without refetching from the server again.

For example, on the code below. I wanted to update PersonTwo's age.

state = {
  users: [
    {
      name: PersonOne,
      age: 1
    },
    {
      name: PersonTwo,
      age: 1
    }
  ]
}
Nar
  • 127
  • 4
  • 15
  • Possible Duplicate of [How to update a nested state in React](https://stackoverflow.com/questions/43040721/how-to-update-a-nested-state-in-react/43041334#43041334) – Shubham Khatri May 29 '18 at 10:15

3 Answers3

0

The best way is to do as you are doing right now that first send the values to the server and then fetch the latest data from the database because if you update the view before successful update on the server you might end up showing which does not exist actually. There is a possibility that your server did not accept that change but somehow you updated the view on user request. It is not a good thing, but if you still want to do that follow the steps below:

step-1: check the array index on which the update of user data is done and then

const newArray = Array.from(this.state.oldArray);
newArray[i] = 'test';

step-2: assign this new array to the old one:

this.setState({oldArray: newArray})
Aniruddh Agarwal
  • 900
  • 1
  • 7
  • 22
  • Yeah, I thought of that as well. But I kind of wanted the front-end to show data without the need of refetching as much as possible. I did however only added the refetch command once the backend confirms that the data I submitted as succesfully added to the database. – Nar May 29 '18 at 10:53
  • Actually, that is the right approach but if you want you can implement the approach I have mentioned. – Aniruddh Agarwal May 29 '18 at 10:56
  • Yeah, I'll give it a try once I get back to work. Thanks btw. – Nar May 29 '18 at 10:56
0

Let's say you have id field in your object. You can use map function to return new array and save it to your state.

updateUser(userId){
  const updatedUsers = this.state.users.map( (user) => {
        if(userId !== user.id) {
            return user;
        }
        return {
            ...user,
            //write some updated info here, for example:
            age: 40
        }
    }):  
    this.setState({
        users: updatedUsers
    }); 
});
Ihor Lavs
  • 2,315
  • 2
  • 15
  • 26
0

You can use functional setState as a success callback of POST/PUT call.

this.setState(prevState => {
   users: ... // operation using prevState.users
})