7
class Signup extends React.Component {
  constructor() {
    super();
    this.state = { count: 0 }
  }

  hndlChange() {
    //here it's okay, It increasing count value
    this.setState({ count: this.state.count + 1 });

    //but here it printing previous value
    console.log(this.state.count);

  }
}

I am calling this function. As it is increasing count value but when I access this it return previous value. i wan to access latest updated value in same function what should i do for that.

How to access latest state value in same function

Ahsan Ali
  • 4,951
  • 2
  • 17
  • 27
Kailash Choudhary
  • 570
  • 2
  • 7
  • 15

2 Answers2

15

As stated here React has additional callback parameter.

Also, when you want to mutate your state using current value you should use function version:

this.setState(currentState => ({ count: currentState.count + 1 }), () => {
    console.log(this.state.count);
});
pwolaq
  • 6,343
  • 19
  • 45
  • this.setState(currentState => ({ count: currentState.count + 1 }), { console.log(this.state.count); }); yah its is the recommended way to update previous state, but i want to get latest value. in your case it showing Unexpected token, expected , ERROR – Kailash Choudhary Jan 18 '18 at 11:05
  • this.setState(currentState => ({ count: currentState.count + 1 }),function() { console.log(this.state.count); }); now its work fine. Thanks @pwolaq – Kailash Choudhary Jan 18 '18 at 11:22
  • @KailashChoudhary I forgot about `() =>` before function body – pwolaq Jan 18 '18 at 11:39
  • 1
    what about useState() hook updater? – King Rayhan Aug 09 '21 at 14:46
2
 hndlChange();
{
  //here it's okay, It increasing count value
  this.setState({ count: this.state.count + 1 }, () => {});
}

set state is asynchronous.

simbathesailor
  • 3,681
  • 2
  • 19
  • 30