Unable to clear "required" error #11280
Unanswered
kwankwankwok
asked this question in
Q&A
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello guys. I am new to react hook form and I am here looking for some help.
Background:
I have two MUI Select in the form: Country and State respectively. Country is set to "required" all over the time. State is only set to "required" after user selected a country and that country is having a state.
Issue:
When user select a country that has a state (eg, Australia), the State field is set to "required". After that, if the user changes the country to another option and that country option is not having a state, the state field is showing the "required" error. I tried "clearErrors", "resetField" , they both work until the user submit the form. Even if "formState.errors" is clear, after clicking the submit button, the "onError" is triggered and "formState.errors" show up the "state" "required" error again !!!! But if the user never select a country that has a state, everything is fine.
Code:
const [stateList, setStateList] = useState([]);
const currCountryCity = formObj.watch("countryCode");
useEffect(() => {
(async () => {
if (currCountryCity) {
formObj.setValue("state", "");
const data = await configHelper.getStatesList(currCountryCity); // api to get the states of the selected country, return an array.
const constructedList = constructList(data); // reform the array
setStateList(constructedList);
if (constructedList.length === 0 && formObj.formState.errors.state) {
console.log("state list is length 0 but state has error");
formObj.resetField("state", { keepTouched: false , keepError: false });
formObj.clearErrors("state");
console.log("clear error", formObj.formState.errors); // log: clear error {}
}
}
})();
}, [currCountryCity]);
function onError(data) {
console.log(data);
}
const isRequired = stateList.length > 0;
return (
<form onSubmit={handleSubmit(onSubmit, onError)} >
<Controller
name="state"
control={control}
rules={isRequired ? { required: requiredMessage } : {}}
defaultValue={inputField.default ?? ""}
render={({ field }) => (
<CustSelect
options={inputField.options}
disabled={inputField.disabled}
inputProps={inputField.inputProps}
defaultValue={inputField.default ?? ""}
label={isRequired ? requiredFieldName : inputField.label}
field={field}
/>
)}
/>
<CustButton
onClick={handleSubmit((d) => onSubmit(d), onError)}
>
Confirm
</CustButton>
</form>
)
Sorry for poor English. Please help me to figure this out.
Beta Was this translation helpful? Give feedback.
All reactions