0

I'm using react-datepicker to building my application.

Follow my source code here: https://codesandbox.io/s/xr76olj70o

I wanna get an object with startDate and endDate when I choose a specified day like this: {startDate: "24-07-2018", endDate: "31-07-2018"}

My handleSelected function like this:

  handleRangeSelected = () => {
    const { startDate, endDate } = this.state;
    const range = {
      startDate: moment(startDate).format("DD-MM-YYYY"),
      endDate: moment(endDate).format("DD-MM-YYYY"),
    }
    console.log('Range selected!', range);
  }

My problem is when I choose a day. At the first time, state seem isn's update immediately when I pick a day.

Results:

First time: I chose 31/07/2018, it logs result:
Range selected! {startDate: "24-07-2018", endDate: "24-07-2018"}


Second time: I chose 01/08/2018, it logs result:
Range selected! {startDate: "24-07-2018", endDate: "31-07-2018"}

What did I wrong here? Need your help! thanks.

Thuan Nguyen
  • 876
  • 3
  • 16
  • 32

3 Answers3

0

Your state seems to be updating correctly, but bear in mind that setState is async, so when you console.log inside your handleRangeSelected, state is not updated yet.

If you want to log it as soon as it updates, you can pass a callback to your setState inside handleChange:

handleChange = ({ startDate, endDate }) => {
  startDate = startDate || this.state.startDate;
  endDate = endDate || this.state.endDate;
  if (startDate.isAfter(endDate)) {
    endDate = startDate;
  }
  // Pass callback to log selected range
  this.setState({ startDate, endDate }, () => {
    const range = {
      startDate: moment(this.state.startDate).format("DD-MM-YYYY"),
      endDate: moment(this.state.endDate).format("DD-MM-YYYY")
    };
    console.log("Range selected!", range);
  });
};
fsl
  • 3,250
  • 1
  • 10
  • 20
0

React setState is asynchronous as a result there you'll face such problems, setState takes a callback as its second argument, you can call the handleRangeSelected function in that callback

You can check https://codesandbox.io/s/011x911nyl i have just logged "state updated" in the callback, just change it to call handleRangeSelected

Avinash
  • 1,864
  • 2
  • 21
  • 27
0

Edit 6zkxr91njw

You are calling onChange and onSelect in your DatePickers. they both fire at the same time so the one who set the new State is fired and the other use the old state values. I changed your code to call handleRangeSelected in the setState callback in handleChange

this.setState({ startDate, endDate }, this.handleRangeSelected);
Jayffe
  • 1,269
  • 9
  • 13