So I'm trying to make a list of contacts, here's the code:
Yup Schema:
export const Schema = Yup.object().shape({/**other fields */contacts: Yup.array().required('Required field').of( Yup.object().required('Required!').shape({ id: Yup.number(), name: Yup.string().required('Required field!'), phone: Yup.string().required('Required field!'), email: Yup.string().email('Type a valid Email!').required('Required field!') }))})
Formik Component:
const Form = () => {return (<View> <Formik validationSchema={Schema} initialValues: { /* other values */ contacts: [ { id: 0, name: '', phone: '', email: '' } ] }>{({ handleChange, handleBlur, handleSubmit, setFieldValue, errors, touched, values }) => { function addNewContact() { setFieldValue('contacts', [ ...values.contacts, { id: values.contacts[values.contacts.length - 1].id + 1, name: '', phone: '', email: '' } ]) } return ( /**A lot of inputs here*/ {values.contacts.map(({ id, email, name, phone }, index) => (<View key={id}><Text>Name *</Text><Input value={name} onChangeText={handleChange(`contacts[${index}].name`)} onBlur={handleBlur(`contacts[${index}].name`)} /> {(errors.contacts ? errors.contacts[index].name : false)&& (touched.contacts ? touched.contacts[index].name : false)&& <Text>{`${errors.contacts[index].name}`}</Text>} /**Repeat the above with phone and email */</View> ))} )}}</Formik></View>)}export default Form
My problem is when displaying the errors, I can't access them. In the way that is written above, intellisense says that name
from errors.contacts[index].name
does not exist on type string | FormikErrors<IContactProps>
I've tried to remove the ternary operator condition, but it tells me that contacts is possibly undefined.
When I console.log(errors.contacts)
, it shows the array I was supose to be able to access with errors.contacts[index].name
.
Even with that intellisense error, my code runs and works with 1 contact. When I add 2 or more contacts,the app throws when I text on an Input: undefined is not an object (evaluating errors.contacts[index].nome)
How can I properly access these errors on an Array of objects? Thanks for your help!