setState
is asynchronous.
If you call setState
and immediately use this.state
, chances are it will not be updated yet.
If you want to set the state and immediately act on that change, you can pass in a callback function.
So, in your case his code will work:
handleFromChange(from) {
this.setState({ from }, () => console.log(this.state));
}
Docs:
setState()
does not immediately mutate this.state but creates a
pending state transition. Accessing this.state
after calling this
method can potentially return the existing value. There is no
guarantee of synchronous operation of calls to setState
and calls may
be batched for performance gains.