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();
}
};