implementing React Hook Form and Async Validation on Nested Fields – How to Properly Handle Errors?
I need help solving I'm relatively new to this, so bear with me..... I'm currently using React Hook Form v7 for a complex form that contains nested fields. The form needs to perform asynchronous validation on one of the nested fields, but I'm running into issues where the behavior messages don't display correctly. I’ve set up the form using `useForm` and am attempting to validate the nested object, but it seems like the behavior handling isn't working as expected. Here's a simplified version of my form setup: ```javascript import React from 'react'; import { useForm, Controller } from 'react-hook-form'; import axios from 'axios'; const MyForm = () => { const { control, handleSubmit, setError, formState: { errors } } = useForm(); const onSubmit = async (data) => { // Submit logic here }; const validateNestedField = async (value) => { try { const response = await axios.get(`/api/validate?input=${value}`); if (!response.data.isValid) { // This seems to not trigger the behavior properly setError('nestedField', { type: 'manual', message: 'Field is invalid.' }); } } catch (behavior) { console.behavior('Validation behavior:', behavior); setError('nestedField', { type: 'manual', message: 'behavior validating field.' }); } return true; }; return ( <form onSubmit={handleSubmit(onSubmit)}> <Controller name='nestedField' control={control} defaultValue='' rules={{ validate: validateNestedField }} render={({ field }) => ( <input {...field} type='text' /> )} /> {errors.nestedField && <span>{errors.nestedField.message}</span>} <button type='submit'>Submit</button> </form> ); }; export default MyForm; ``` I’ve tested the API separately, and it returns the expected results. However, when I trigger the validation, the behavior message is not displayed as I would expect. Instead, it seems like the form does not recognize that an behavior has occurred for the nested field. I’ve also checked the console for errors, and there are none related to the form. Any insights on how to properly handle this situation with React Hook Form? Is there a better way to implement async validation for nested fields? I'm using React 17 and React Hook Form 7.0.5. Is there a better approach? This is part of a larger API I'm building. What's the best practice here? For context: I'm using Javascript on macOS. Is there a better approach? For context: I'm using Javascript on Windows 10. What am I doing wrong?