Formik with Yup Validation: implementing Asynchronous Validation of Nested Fields
I tried several approaches but none seem to work... I'm working through a tutorial and I'm currently using Formik (v2.2.6) alongside Yup (v0.32.9) for handling my form validations in a React application. The form contains nested fields for a user profile that includes an array of addresses. The asynchronous validation on one of the nested fields is not working as expected, causing the form to submit despite validation errors appearing only after the user interacts with the input. Hereβs a simplified version of my form setup: ```javascript import React from 'react'; import { Formik, Field, Form, ErrorMessage } from 'formik'; import * as Yup from 'yup'; const validationSchema = Yup.object().shape({ userProfile: Yup.object().shape({ addresses: Yup.array().of( Yup.object().shape({ street: Yup.string().required('Street is required'), city: Yup.string().required('City is required'), zip: Yup.string().required('ZIP is required').test('is-valid-zip', 'ZIP is not valid', async (value) => { const response = await fetch(`/api/validate-zip/${value}`); const data = await response.json(); return data.isValid; }), }) ), }), }); const MyForm = () => { return ( <Formik initialValues={{ userProfile: { addresses: [{ street: '', city: '', zip: '' }] } }} validationSchema={validationSchema} onSubmit={(values) => { console.log(values); }} > {({ isSubmitting }) => ( <Form> <Field name="userProfile.addresses[0].street" placeholder="Street" /> <ErrorMessage name="userProfile.addresses[0].street" component="div" /> <Field name="userProfile.addresses[0].city" placeholder="City" /> <ErrorMessage name="userProfile.addresses[0].city" component="div" /> <Field name="userProfile.addresses[0].zip" placeholder="ZIP" /> <ErrorMessage name="userProfile.addresses[0].zip" component="div" /> <button type="submit" disabled={isSubmitting}>Submit</button> </Form> )} </Formik> ); }; ``` The question arises when I input a ZIP code that is invalid. Even though the validation is asynchronous, the form allows submission without waiting for the validation to complete. I expected the form to prevent submission until all validations, including the async one, were resolved. I've tried ensuring that the test method returns a boolean correctly, and I've placed console logs in both the test and the submit handler to trace the flow. However, the form submits regardless of the validation state. Has anyone encountered a similar scenario or knows how to handle asynchronous validations properly in nested fields using Formik and Yup? Any help would be greatly appreciated! Has anyone dealt with something similar? For reference, this is a production desktop app. What would be the recommended way to handle this? This is happening in both development and production on Ubuntu 20.04. Any pointers in the right direction?