I am validating fields with react-hook-form and besides having fields as required, I also run the toast to show user that field is required.
I use the following function to achieve it:
const runError = () => {
if (!isValid && Object.keys(errors).length > 0) {
toast.error("Please fill required fields", {
icon: <ErrorIcon />,
closeButton: <CloseIcon />,
});
return <div></div>;
} else {
return null;
}
};
and then call {runError()} in JSX.
it works but issue is that when I fill required field, toast still runs once after that. Why?
I have onPost={handleSubmit((data) => handleFormSubmit("post", data))} and also
const handleFormSubmit = async (
action: "save" | "post",
data: TestModel
) => {
if (action === "save") {
const newModel: TestDto = { ...model, ...data };
await saveHandler(newModel);
} else if (action === "post") {
const newModel: TestDto = { ...model, ...data };
await saveHandler(newModel);
await postHandler();
}
};
2
Answers
when handleFormSubmit updates the state, it triggers a re-render, causing runError() to be called again, even if the required field has already been filled in. This results in the error message being displayed twice.
To fix this issue, you can try using the useEffect hook to call runError() only when the form has been submitted and the errors have changed
May be you have to turn off strict-mode as react rerenders your component twice in strict-mode to help catch any errors