'Formik FieldArray error messages - React Native

I'm using Formik FieldArray as part of my form and would like to show error messages, I can access the error messages within a component via errors.familyMembers[0], which looks like

[{"first_name": "First Name is a required field", "last_name": "Last Name is a required field"}]

To show the error I have 2 parts where I need to extract the error message

isInvalid={fieldName in errors.familyMembers[0] && touched[fieldName]}

<FormErrorMessage
  message={errors.familyMembers[0][fieldName]}
  isVisible={touched[fieldName]}
/>

The problem is when the component is initially rendered errors.familyMembers[0] is undefined, which gives me the error

undefined is not an object (evaluating 'errors.familyMembers[0]')

Is there a way I can guard against undefined and have the messages show if available? Hope that makes sense



Solution 1:[1]

You can use Optional chaining, like:

isInvalid={errors?.familyMembers && fieldName in errors.familyMembers[0] && touched[fieldName]}

<FormErrorMessage
  message={errors?.familyMembers?.[0][fieldName]}
  isVisible={touched[fieldName]}
/>

The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CD..