'Clicking Cancel on Date/Timer react-native-community/datetimepicker throws an error

Upon clicking on cancel or the opacity background on <DateTimePicker />, throws an error.

is there a callback to cancel ?

i dont see anything about cancel in react-native-community/datetimepicker docs

react-native-community/datetimepicker : 3.4.3

date-fns : 2.19.0

here's my code

  function NewAppointmentScreen () {
    const [date, setDate] = useState(new Date(Date.now()));
    const [showCalendar, setShowCalendar] = useState(false);
  
    const onChangeDate = (e, selectedDate) => {
      setShowCalendar(false);
      setDate(selectedDate);
    };
    
    const onPressCalendar = () => {
      setShowCalendar(true);
    }
    return {
      <View style={styles.container}>
        //callback 
        <View style={{ width: '48%' }}>
            <CustomInput
              editable={false}
              title="Date"
              value={format(date, 'MM/dd/yyyy')}
              leftIcon={
                <Icon
                  color={THEME.PRIMARY}
                  name="calendar"
                  type={ICON.MaterialCommunityIcons}
                />
              }
              onPressIcon={onPressCalendar}
            />
          </View>
      
          {showCalendar && (
          <DateTimePicker
            display="default"
            mode={'date'}
            style={styles.datePicker}
            value={date}
            onChange={onChangeDate}
          />
        )}
      </View>
    }
  }
  


Solution 1:[1]

If anyone finds this question, you should check if the value is valid before setting the state:

const onChangeDate = (e, selectedDate) => {
  setShowCalendar(false);
  selectedDate && setDate(selectedDate);
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matheus Melo