I am having trouble passing the selected date in React Native component that is encapsulated with Formik. It seems that the value is not passed even though the field value changed and the console log shows the selected date. See image. Please help as I can't seem to understand where it should be defined/changed. I will post the two script files AppDatePicker.js and AppFormDate.js (the latter which encapsulates the former with Formik for validation and errors).
AppDatePicker.js
function AppDatePicker({ icon, placeholder, }) {
const [date, setDate] = useState(new Date());
const [mode, setMode] = useState();
const [show, setShow] = useState(false);
const [title, setTitle] = useState(placeholder)
const onChange = (selectedDate) => {
const currentDate = selectedDate || date;
setShow(Platform.OS === 'ios');
setDate(currentDate);
let tempDate = new Date(currentDate);
let fDate = tempDate.getFullYear() + '-' + (tempDate.getMonth() + 1) + '-' + tempDate.getDate();
console.log(fDate)
setTitle(fDate.toString())
}
const showMode = (currentMode) => {
setShow(true);
setMode(currentMode);
}
return (
<View>
<TouchableWithoutFeedback onPress={() => showMode('date')}>
<View style={styles.container}>
{icon &&
<MaterialCommunityIcons name={icon} size={20} color={colors.black} style={styles.icon}>
</MaterialCommunityIcons>
}
{
onChange ? (
<AppText style={styles.text}>{title}</AppText>
) : (
<AppText style={styles.placeholder}>{placeholder}</AppText>
)
}
<MaterialCommunityIcons name="chevron-down" size={20} color={colors.black}></MaterialCommunityIcons>
</View>
</TouchableWithoutFeedback>
{show &&
<DateTimePicker
value={date}
mode={mode}
display='default'
onChange={(_, date) => onChange(date)}
onPress={date}>
</DateTimePicker>
}
</View>
);
}
AppFormDate.js
import React from 'react';
import { useFormikContext } from 'formik';
import AppErrorMessage from './AppErrorMessage';
import AppDatePicker from './AppDatePicker';
function AppFormDate({ name, placeholder }) {
const {errors, setFieldValue, touched, values} = useFormikContext();
return (
<React.Fragment>
<AppDatePicker
onSelectItem={(date) => setFieldValue(name, date)}
placeholder={placeholder}
selectedItem={values[name]}>
</AppDatePicker>
<AppErrorMessage
error={errors[name]}
visible={touched[name]}>
</AppErrorMessage>
</React.Fragment>
);
}