0

I am trying to implement a cancel feature, where if a user clicks outside the react-dates date picker calendar something happens.

In my calendar component I am setting state for two properties - startDate and endDate but endDate doesn't get set on the state. If I add breakpoints I can see it hits this and tries to set it with a value. If I add the callback function for state being updated, this never gets run, so something weird is happening that I can't resolve.

Why would state not update? There are no errors in the console.

Example code from my calendar component:

onDatesChange = ({ startDate, endDate }) => {
    this.setState({ startDate, endDate });
    if (startDate && endDate) {
        this.props.onDatesPicked(startDate.format('YYYY-MM-DD'), endDate.format('YYYY-MM-DD'));
    }
};

onClose = () => {
    const { startDate, endDate } = this.state;
    if (!startDate || !endDate) {
        this.props.onCancel();
    }
};

render() {
    const { startDate, endDate, focusedInput } = this.state;

    return (
        <div className={css.component}>
            <DateRangePicker
                displayFormat="DD MMM YYYY"
                isOutsideRange={this.isOutsideRange}
                startDate={startDate}
                startDateId={START_DATE}
                startDatePlaceholderText="Start date"
                endDate={endDate}
                endDateId={END_DATE}
                endDatePlaceholderText="End date"
                onDatesChange={this.onDatesChange}
                focusedInput={focusedInput}
                onFocusChange={this.onFocusChange}
                firstDayOfWeek={1}
                hideKeyboardShortcutsPanel
                minimumNights={0}
                withPortal
                onClose={this.onClose}
            />
        </div>
    );
}

In the onClose function never finds a value for endDate even though setState has already been called in onDatesChange and has passed in a value. There are no issues with startDate. If I comment out setting startDate then endDate does get set fine.

I am so confused...

Heather Roberts
  • 1,978
  • 1
  • 24
  • 33
  • 1
    Did you check if onDatesChange() method is getting startDate and endDate or not ? – Akshay Aggarwal May 01 '18 at 09:13
  • I was going to ask the same thing: double check the inputs that method is receiving. I wonder if you gave the property names wrong, or if they're actually coming in as two arguments rather than one. – tremby May 01 '18 at 10:21
  • Yeah endDate definitely has a value, I checked this by adding a breakpoint. Also the if block at the end of the function which only runs if both startDate and endDate are truthy runs happily. – Heather Roberts May 03 '18 at 05:52

0 Answers0