I've a formik form in a component that I'd want to reuse. In order to do that I need to listen to the form values changes in order to call two functions, getFormValues
and getFormErrors
, that will be passed by the parent component:
import React from "react";
import * as Yup from 'yup';
import { Formik } from 'formik';
import CheckBox from "@react-native-community/checkbox";
import { Text, TextInput } from "react-native";
import { errorStyle } from "../../styles/form.styles";
export default function UserCredentialForm({getFormValues, getFormErrors}) {
const formSchema = Yup.object().shape({
email: Yup.string().email()
.required('Required'),
password: Yup.string()
.test('lenght', 'min 5chr max 10chr', (val = '') => val.length > 4 && val.length < 11)
.required('Required'),
});
const [state, setState] = React.useState({
form: {
email: '',
password: '',
}
});
const formRef = React.useRef({} as any);
React.useEffect(() => {
console.log('formref', formRef.current.values);
getFormValues(formRef.current.values);
getFormErrors(formRef.current.errors);
}, [formRef.current.values, formRef.current.errors]);
return (
<Formik innerRef={formRef} validationSchema={formSchema} initialValues={state.form} onSubmit={() => {}}>
{({ handleChange, values, touched, errors }) => (
<React.Fragment>
{errors.password && touched.password ? <Text>{errors.email}</Text> : null}
<TextInput
style={errors.email && touched.email ? errorStyle.input : null}
keyboardType='email-address'
onChangeText={handleChange('email')}
value={values.email}
placeholder="email"
/>
{errors.password && touched.password ? <Text>{errors.password}</Text> : null}
<TextInput
style={errors.password && touched.password ? errorStyle.input : null}
onChangeText={handleChange('password')}
value={values.password}
placeholder="password"
secureTextEntry={true}
/>
</React.Fragment>
)}
</Formik>
);
}
As you can see I'm using useEffect
hooks linked to the form ref values, but it get called only once at form first render. What am I missing?
How can I subscribe to all values changes?