Can't acces formik.errors with Yup and array of object

Viewed 433

When I console.log "formik.errors" I have:

Array [ {…} ]
0: Object { firstName: "First name is required", lastName: "Last name is required", email: "Invalid email", … }
email: "Invalid email"
firstName: "First name is required"
lastName: "Last name is required"
password: "Password is required"

but when I try to access "formik.errors.employee[0].email" I have this error:

Property 'email' does not exist on type 'string | FormikErrors<{ lastName: string; firstName: string; email: string; password: string; }>'.
  Property 'email' does not exist on type 'string'.

Here is my yup schema:

Yup.object().shape({
  employee: Yup.array().of(
    Yup.object().shape({
      firstName: Yup.string().required('First name is required'),
      lastName: Yup.string().required('Last name is required'),
      email: Yup.string()
        .email('Invalid email')
        .required('Email is required'),
      password: Yup.string()
        .required('Password is required')      
    })
  ),

What is wrong with my schema ?

1 Answers

So looks like it's an issue : https://github.com/jaredpalmer/formik/issues/2347

Here is the hack :

  <TextField
        id='email'
        name='employee[0].email'
        label='Email'
        onChange={formik.handleChange}
        value={formik.values.employee[0].email}
        error={formik.touched.employee && Boolean((formik.errors.employee?.[0] as Employee)?.email)}
        helperText={(formik.errors.employee?.[0] as Employee)?.email}
 />
Related