javascript – Setting React state within handleSubmit callback using react-hook-form
I’m building some user inputs for a client-side application with react-hook-form.
Users should be able to update an input. Then onBlur, react-hook-form is to validate the input and update an react useState object. If validation fails, the external state is not updated.
The following code fails to keep the external state object up to date onBlur.
As the handleSubmit() function is async, i’m unable to set the state.
function App() {
const [value, setValue] = useState({
name: "",
});
const { register, handleSubmit } = useForm({ mode: "onBlur" });
return (
<>
{errors?.name ? {errors.name.message}
: null}
{
setValue((prev) => ({ ...prev, name: data.name }));
}),
minLength: { value: 2, message: "Name is too short" },
required: { value: true, message: "Name is required" },
})}
id="name"
type="text"
/>
>
);
}
- I’ve tried wrapping handleSubmit in async / await – however this doesn’t yield anything as the handleSubmit method will only expose the result to the callback function.
- useEffect on the react-hook-form watch() function; issue with this is you dont get the validation.
- Creating my own synchronous methods to validate seem to defeat the purpose of using react-hook-form.
Read more here: Source link
