saed hossam
saed hossam

Reputation: 11

can't bind Formik Validations Errors for an array of object

I have a form that contains two fields: boolean value and array of objects. when the boolean value is true then the array should be required. and the array have two string fields one is required and the other is not.

Validation Schecma

  const validationSchema = Yup.object().shape({
    boolVal: Yup.boolean().required().nullable(),
    arr: Yup.array().when('boolVal', {
      is: true,
      then: Yup.array(
        Yup.object().shape({
          str1: Yup.string().nullable(),
          str2: Yup.string().required()
          ),
        })
      ),
    }),
  })

initialValues

const formik = useFormik({
    initialValues: 
                  {
                    boolVal:false,
                    arr: [new MyObject()]
                  }
})

when i try to render the error for a specific element of the array like this

formik.errors.arr[0]

i got this error

Uncaught Error: Objects are not valid as a React child (found: object with keys {str2}). If you meant to render a collection of children, use an array instead.

and when i hover over the 'arr' to see the type of it, it gives me

(property) arr?: string | string[] | FormikErrors < MyObject > []

when i render the errors using this line of code

{JSON.stringify(formik.errors.arr)}

it shows me

{ "arr" : [ { "str2": "str2 is required" } ] }

Upvotes: 0

Views: 2529

Answers (1)

Yash Narola
Yash Narola

Reputation: 107

I was facing a similar issue but I solved it using getIn.

You can use it by following:

import { getIn } from 'formik';

getIn(formik.errors, 'arr[0]');

enter image description here

To refer formik documentation:https://formik.org/docs/api/fieldarray#fieldarray-validation-gotchas

Upvotes: 2

Related Questions