Using React setState to handle error validation & handling

Viewed 193

validation on components is currently being handled in a "base component", which wraps children in "error state" and passes inError props to them.

Currently the check for showErrors is done like so:

let showErrors = (component.hasServerErrors()) && (!hasFocus || component.type === "radio");

This basically means that when a page is submitted, the hasServerErrors() method is run which checks for errors on the server (not handled by UI).

This works fine for the first time a page is validated (user doesn't select a radio) - error messaging appears fine, but because hasServerErrors() only runs on submission of the page, the error state persists after a value is changed.

I made the following update to improve this behaviour:

const [resolvedErrors, setResolvedErrors] = useState(false);

let showErrors = (!resolvedErrors ? component.hasServerErrors() : false) && (!hasFocus || component.type === "radio");

  const handleChange = (e: SyntheticEvent<FormInputElements>) => {
    handleEvent(onChange, e.currentTarget.value);

    if (hasFocus && showErrors) {
      setResolvedErrors(true);
    }
  };

This solved my issue of "resolving" the error state meaning that when an element was inError, and they selected a valid option, the error state would disappear. However, it's not a robust solution as if a user selects a valid option, then de-selects it, this is not picked up and means the user is no longer aware what element is in error.

Can anyone suggest a way I could combine showErrors and resolvedErrors into one concise state, so that error handling could be properly managed?

0 Answers
Related