Reputation: 605
I am using react-native-calendar-picker
The issue is:-
When I am selecting for the first time it is giving correct date for both startDate and endDate.
But after first time startDate is giving null.
My component code is:-
<CalendarPicker
startFromMonday={true}
allowRangeSelection={true}
onDateChange={onDateChange}
/>
my state code is:-
const [state, setState] = React.useState({
startDate: null,
endDate: null,
})
My function is:-
const onDateChange = (date, type) => {
console.log("changed date", moment(date).format("MM/DD/YYYY"));
if (type === 'END_DATE') {
setState({
...state,
endDate: date,
});
} else {
setState({
...state,
startDate: date,
endDate: null,
});
}
}
Upvotes: 0
Views: 472
Reputation: 125
I believe you are getting wrong somewhere when setState. I have created a working snack demo for you, please check if this solves your problem.
Here is the snack link.
Upvotes: 0
Reputation: 580
Not sure if this will solve the issue, since I don't see the complete code. Please try using a function to setState so that you are guaranteed you get the previous state prior to setting the new state. React processed setStates in batches. I am not sure if the issue lies here but try this else we may look at other options
const onDateChange = (date, type) => {
console.log("changed date", moment(date).format("MM/DD/YYYY"));
if (type === "END_DATE") {
setState((prevState) => {
return { ...prevState, endDate: date };
});
} else {
setState((prevState) => {
return {
...prevState,
startDate: date,
endDate: null,
};
});
}
};
Upvotes: 0