5

I have a simple React component which has a input field with an onChange event attached. The onChange event fires, and updates the some component state with the value from the input field. However i noticed when console logging that the state is one character behinde. So if i type "Hello" the console shows the state to be

'' on H

'H' on HE

'E' on HEL

'L' on HELL

'L' on HELLO

How is that?

Fripo
  • 173
  • 1
  • 4
  • 13
  • Possible duplicate of [How to get value of selected option in react-bootstrap select FromControl](https://stackoverflow.com/questions/45612278/how-to-get-value-of-selected-option-in-react-bootstrap-select-fromcontrol) – Adrien Lacroix Aug 10 '17 at 20:32
  • Possible duplicate of [setState doesn't update the state immediately](https://stackoverflow.com/questions/41278385/setstate-doesnt-update-the-state-immediately) –  Jun 26 '19 at 13:07

1 Answers1

10

this.setState is asynchronous. It means that the time console logged could not be matched with the time state got updated If you want to see exact value after state got changed, you have to do as below

this.setState({ 'updated': 'state'}, () => {
  console.log(this.state.updated);
});
ZeroCho
  • 1,358
  • 10
  • 23