I have a form that accepts 5 values keyed in by the user. The sum of the first 4 values must match the 5th one.
valueA + valueB + valueC + valueD == valueE
If they don't, an error message pops up. The checking is in real-time and begins when the user keys in the value.
This is my code:
const {
control,
watch,
getValues,
setValue,
setError,
clearErrors,
formState: { errors, isDirty },
} = useForm({})
const watchValues= watch(["valueA", "valueB", "valueC", "valueD", "valueE"]);
useEffect(() => {
let val1 = getValues("valueA") ? parseFloat(getValues("valueA")) : 0.0;
let val2 = getValues("valueB") ? parseFloat(getValues("valueB")) : 0.0;
let val3 = getValues("valueC") ? parseFloat(getValues("valueC")) : 0.0;
let val4 = getValues("valueD") ? parseFloat(getValues("valueD")) : 0.0;
let val5 = getValues("valueE") ? parseFloat(getValues("valueE")) : 0.0;
let compareValue = Boolean((val1 + val2 + val3 + val4 ).toFixed(2) === val5.toFixed(2));
if (!compareValue) {
setError("valueE", {
type: "manual",
message: "Error",
});
} else clearErrors("valueE");
}, [watchValues]);
Before declaring formState: { errors, isDirty },, specifically errors, this was working as intended.
After adding errors to the formState, I started getting Maximum update depth exceeded issues.
I know why the error happens, but I can't see why would it happen here, what would cause the loop. I've only managed to pinpoint the issue to the setError / clearError if-else statement.
The end result I'm trying to reach is to stop the form from submitting only while the values do not match (so, if all fields are blank, that would be a valid input).
try useWatch hook from react-hook-form , https://react-hook-form.com/api/usewatch. It will help you with the re-rendering and also, put the result from it in the useEffect deps.
const watchValues = useWatch({control,});
useEffect(()=>{ ... what you have...}, [watchValues])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With