0

I'm wondering why setState is not working for a specific property.

In my componentWillReceiveProps(nextProps), I'm setting the state for various state variables. But only one of them is not getting set. But, when I print the nextProps, I can clearly see the updated props for the specific state variable.

eg:

this.state = {
    job: { jobId: null, name: null},
    list: { items: null, total: null}
}

componentWillReceiveProps(nextProps) {
// When I print nextProps, it is showing the updated prop value
    /* nextProps: {
                   job: 
                      {
                        jobId: 123, 
                        name: "sai"
                      }, 
                   list: 
                      {
                        items: 25, 
                        total: 150
                      }
                  }
      */

 this.setState({
      job: nextProps.job,
      list: nextProps.list
 });
 console.log(this.state.job); // gives me -> job: { jobId: null, name: null}
 console.log(this.state.list); // gives me -> list: { items: 25, total: 150}
}

When I print the output to console this.state.job, it is printing the initial state not the updated state. I'm not sure how to figure this out.

Sai
  • 81
  • 1
  • 8
  • That’s because setState is asynchronous, you should try use the new syntax. `this.setState((prevState) => { return { job: nextProps.job, list: nextProps.list} }); – Jacobo May 23 '18 at 05:32

2 Answers2

1

use the callback while you set state because setState is asynchronous and you will have to wait for the result until it finishes its job.

this.setState({
      job: nextProps.job,
      list: nextProps.list
 },function(){
  console.log(this.state) //here you will get updated values.
 });
Manoz
  • 6,507
  • 13
  • 68
  • 114
0

That is because setState works asynchronously and it hasn't finished setting the new state yet when you log it.

Try doing this an see the log

this.setState({
      job: nextProps.job,
      list: nextProps.list
 },()=>console.log(this.state);
supra28
  • 1,646
  • 10
  • 17