I'm working on a react-native project and I am using mmazzarolo/react-native-modal-datetime-picker
To change state I am doing this,
export default = () => {
const [getDate, setGetDate] = useState(null)
const [isDatePickerVisible, setDatePickerVisible] = useState(false)
const showDatePicker = () => setDatePickerVisible(true);
const hideDatePicker = () => setDatePickerVisible(false);
const handleConfirm = (date) => {
setGetDate(format(new Date(date), 'MM/dd/yyy'));
hideDatePicker();
}
}
//This is how I'm implementing the datepicker with React Hook Form.
{isDatePickerVisible ? (
<Controller
control={control}
render={({ onChange, onBlur, value }) => (
<DateTimePickerModal
isVisible={isDatePickerVisible}
mode="date"
onConfirm={handleConfirm}
onCancel={hideDatePicker}
/>
)}
name="apptDate"
rules={{ required: true }}
defaultValue=""
/>
) : (
<Controller
control={control}
render={({ onChange, onBlur, value }) => (
<TextInput
style={styles.input}
onTouchEnd={showDatePicker}
onChangeText={value => onChange(value)}
value={getDate}
/>
)}
name="apptDate"
rules={{ required: true }}
defaultValue=""
/>
)
}
When I open the modal and press Confirm on today's date (the current date) it returns null but after the second time I get the date I want.
I believe it's because I'm not updating the previous state using the function way to update the state and I'm having trouble figuring out how to update the previous state of null to the new Date() as a function.