0

After the first date selection the selected date is not displayed on console and delayed and only set on state on the next selection.

This is the link to my code. go to sample code

Am i missing something? I expect it to display on console on the first selection.

1 Answers1

2

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.

Dan Cantir
  • 2,915
  • 14
  • 24