How to get the value of date from @react-native-community/datetimepicker and store it in for a user in an object

1.3k Views Asked by At

I am building a signup page for users where they can select their date of birth from the datepicker which I used from '@react-native-community/datetimepicker'. Everything is working fine and the code is able to display the selected date on the screen, also every other field's data is getting stored in the userInfo object except the dateOfBirth. Here is the part of code where I used the datepicker:

(You can ignore formatDate function as it just formats the date out of timestamp)

            <Text style={[styles.text_footer,{marginTop:10}]}>Date Of Birth</Text>
            <View style={[styles.action,{paddingTop:5}]}>
                <FontAwesome
                name="calendar"
                color="#05375a"
                size={20}
                onPress={showDatepicker}
                />
                {show && (
                    <DateTimePicker
                    testID='dateTimePicker'
                    value={date}
                    mode={mode}
                    is24Hour={true}
                    display='default'
                    onChange={onChange}
                    //onChange={(val)=>handleOnChangeText(val,'dateOfBirth')}
                    />
                )}
                <Text style={[styles.textInput,{paddingTop:10}]}>{formatDate(date)}</Text>
            </View>

And the functions and states used are:

    const [date, setDate] = useState(new Date());
    const [mode, setMode] = useState('date');
    const [show, setShow] = useState(false);

    const [userInfo, setUserInfo]=React.useState({
        email:'',
        password:'',
        gender:'',
        age:null,
        dateOfBirth:'',
        address:'',
        role:'',
        check_textInputChange:false,
        secureTextEntry:true,
        isValidUser: true,
        isValidPassword: true,
        isValidAge:true,
        isValidAddress:true
    });

    const {email,password,gender,age,dateOfBirth,address,role}=userInfo;


    const onChange = (event, selectedValue) => {
        setShow(Platform.OS === 'ios');
        if (mode == 'date') {
          const currentDate = selectedValue || new Date();
          setDate(currentDate);
        } 
      };
    const showMode = currentMode => {
        setShow(true);
        setMode(currentMode);
      };
    const showDatepicker = () => {
        showMode('date');
      };
    const handleOnChangeText= (val,fieldname)=>{
        setUserInfo({...userInfo,[fieldname]:val})
        //console.log(val,fieldname);
    };
//If I console.log(userInfo) here then the state dateOfBirth is not getting updated 

ALSO, an example of email and how I am using handleOnChangeText function:

(THIS IS WORKING. Attached just for understanding purposes, please ignore textInputChange and handleValidUser functions)

            <Text style={styles.text_footer}>Email</Text>
            <View style={styles.action}>
                <FontAwesome
                name="user-o"
                color="#05375a"
                size={20}
                />
                <TextInput
                value={email}
                placeholder="Your Email" 
                style={styles.textInput}
                autoCapitalize="none"
                onChangeText={(val)=>{textInputChange(val);handleOnChangeText(val,'email');}}
                onEndEditing={(e)=>handleValidUser(e.nativeEvent.text)}
                />
                {userInfo.check_textInputChange?
                <Animatable.View
                    animation="bounceIn"
                >
                <Feather
                name="check-circle"
                color="green"
                size={20}
                />
                </Animatable.View>
                :null}
            </View>
            {
                userInfo.isValidUser?null:
            <Animatable.View animation="fadeInLeft" duartion={500}>
             <Text style={styles.errorMsg}>Username must be 4 characters long.</Text>       
             </Animatable.View>
            } 

The object output after logging userInfo

enter image description here

How can I get the value of dateOfBirth in userInfo?

1

There are 1 best solutions below

1
On BEST ANSWER

This is likely due to a minor mistake in your code. The Date change handler that you are passing to DateTimePicker does never call handleOnChangeText:

<DateTimePicker
    testID='dateTimePicker'
    value={date}
    mode={mode}
    is24Hour={true}
    display='default'
    onChange={onChange} // <--- this one
    //onChange={(val)=>handleOnChangeText(val,'dateOfBirth')}
/>

Updating the handler should solve your problem:

const onChange = (event, selectedValue) => {
    setShow(Platform.OS === 'ios');
    if (mode == 'date') {
        const currentDate = selectedValue || new Date();
        setDate(currentDate);
        handleOnChangeText(currentData, 'dateOfBirth') // <--- add this line
    } 
};