Search code examples
androidreact-nativeuse-state

DateTimePickerModal On Working on Android


I have used react-native-modal-datetime-picker to create a calendar view. I have created a state, birthDate to set my date using onChange function in DateTimePickerModal. The problem is the date is getting picked on IOS device but while picking the date in Android the state of birthDate is not changing and it is taking the value which is used while initializing the state that present Date. Below is my code for the same:

const [isDatePickerVisible, setDatePickerVisibility] = useState(false);
const [birthDate, setBirthDate] = useState(new Date());
const showDatePicker = () => {
    setDatePickerVisibility(true);
    chosenDate: ''
  };

  const hideDatePicker = (date) => {
    setDatePickerVisibility(false);
    chosenDate: moment(date).format('DD-MM-YYYY');
  };

  const handleConfirm = (date) => {
    console.warn("A date has been picked: ", date);
    console.log('Type of Date', typeof (date))
    hideDatePicker();
  };

const updateBday = () => {
    console.log("Date", birthDate)
    updateDoc(doc(db, 'users', user.uid), {
      dateOfBirth: birthDate
    }).then(() => {
      navigation.navigate('GenderPage')
    })
      .catch((error) => {
        alert(error.message);
      })
  };

return (
<View style={styles.inputView}>
        <TouchableOpacity style={styles.textInput} onPress={showDatePicker}>
          <AntDesign name="calendar" size={30} color="black" style={styles.calendarIcon} />
          <DateTimePickerModal
            isVisible={isDatePickerVisible}
            mode="date"
            onChange={(date) => setBirthDate(date)}
            onConfirm={handleConfirm}
            onCancel={hideDatePicker}
          />
          <Text style={styles.dateView}>
            {birthDate ? moment(birthDate).format('   MMMM DD, YYYY') : '-'}
          </Text>
        </TouchableOpacity>
      </View>
)

Anyone facing the same issue?


Solution

  • I was facing the same issue where the state of my object was getting changed in IOS but not in Android. I was able to resolve the issue by setting the state of birthDate in handleConfirm function. You can write the function as below:

    const handleConfirm = (date) => {
        console.log("A date has been picked: ", date);
        console.log('Type of Date', typeof (date))
        setBirthDate(date)
        hideDatePicker();
      };
    

    Hope it helps.