Reputation: 835
I have a Ant Design Calendar component in my React project -
<Calendar
value={this.state.value}
fullscreen={false}
onPanelChange={this._onPanelChange}
onSelect={this._onSelect}
disabledDate={(current) => {
return current && moment().isAfter(current, "day");
}}
/>
and I have the following state -
this.state = {
value: moment(),
scheduleDate: moment(),
}
the _onSelect
function looks like -
_onSelect = (value) => {
this.setState({
value,
scheduleDate: value,
});
this.props.setScheduleDate(this.state.scheduleDate.toDate());
console.log(this.state.scheduleDate);
};
When the user selects a date (say, 23rd of April, 2021), the console.log
gives me a date of 22nd April(current default date), 2021. Similarly, when the user selects 24th April, 2021, the console.log
gives 23rd April, 2021.
It always sets scheduleDate
to what was selected in the previous step. Any idea what's wrong and how can I fix it? Thanks in advance.
Upvotes: 0
Views: 723
Reputation: 6019
The issue in your code lies here this.props.setScheduleDate(this.state.scheduleDate.toDate())
because setState
is asynchronous. That means the state
will not get updated as soon as we call setState
. So, the value which you see in the console
or this.props.setScheduleDate
is the previous state value.
Now, there are 2 ways in order to resolve this issue
setState
's callback
method which is the second parameter to setState() is an optional callback function that will be executed once setState is completed_onSelect = (value) => {
this.setState({
value,
scheduleDate: value,
}, () => {
this.props.setScheduleDate(this.state.scheduleDate.toDate());
console.log(this.state.scheduleDate);
});
};
_onSelect
function's parameter while calling this.props.setScheduleDate
_onSelect = (value) => {
this.setState({
value,
scheduleDate: value,
});
this.props.setScheduleDate(value.toDate());
};
Upvotes: 1