Max Wolfen
Max Wolfen

Reputation: 2043

React. How to update the state with previous state?

I'm trying to update the state, based on previous state (array of objects) with the new incoming values in fase of object. But for some reasons it does not happen...

What is I'm doing wrong? My code:

   handleCommentSubmit = (newEmployer) => {
       console.log('handleCommentSubmit BEFORE', this.state.employers, newEmployer); // array(5)
       this.setState((prevState, newEmployer) => { 
         employers: prevState.employers + newEmployer
       });
       console.log('handleCommentSubmit AFTER', this.state.employers); // still array(5)
   }

My log:

handleCommentSubmit BEFORE (6) [{…}, {…}, {…}, {…}, {…}, {…}], newEmployer: {first_name: "sdfsdf", last_name: "sdfsdf", birth_date: "123123-03-12", salary: "123123123"}
handleCommentSubmit AFTER (6) [{…}, {…}, {…}, {…}, {…}, {…}]

Upvotes: 7

Views: 27202

Answers (4)

Trinu
Trinu

Reputation: 1761

if you call the setState it won't update immediately in the next line. It will update after the render method gets called. If you want to see the updatedState you can write a callback function in the setState like this.

this.setState((prevState, newEmployer) => { 
         employers: prevState.employers + newEmployer
       }, () => console.log('UpdatedState', this.state.employers));

Upvotes: 2

Mayank Shukla
Mayank Shukla

Reputation: 104529

Changes:

1- setState is async so use callback to check the updated value.

2- Use [].concat to push a new value in array, + will not work.

3- You are not returning the object from the updater function.

Write it like this:

handleCommentSubmit = (newEmployer) => {
    this.setState((prevState, newEmployer) => ({
        employers: prevState.employers.concat(newEmployer)
    }), () => {
        console.log('handleCommentSubmit AFTER', this.state.employers);
    }); 
}

Check this answer for more details:

Why calling setState method doesn't mutate the state immediately?

Upvotes: 9

Arkej
Arkej

Reputation: 2241

If your employers is an Array you can use spread operator in setState:

[...prevState.employers, newEmployer]

but you don't need prevState at all. You can just:

this.setState({ 
         employers: [...this.state.employers, newEmployer]
       });

Upvotes: 3

Alex Antonov
Alex Antonov

Reputation: 15226

this.setState should receive object as an argument. Not a function. You could easily use this.state:

handleCommentSubmit = (newEmployer) => {
  this.setState({ 
    employers: this.state.employers.concat(newEmployer)
  });
}

Upvotes: -7

Related Questions