Home > other >  How do I prevent this form from being submitted if errors still exist?
How do I prevent this form from being submitted if errors still exist?

Time:09-17

Below function always submit the form at the first render of the component even if firstName and lastName fields are empty.

const [formErrors, setFormErrors] = useState({});

const registerUser = () => {
    if (firstName === "") {
      setFormErrors((prev) => {
        return { ...prev, firstName: "Firstname is required!" };
      });
    }

    if (lastName === "") {
      setFormErrors((prev) => {
        return { ...prev, lastName: "Lastname is required!" };
      });
    }

    if (Object.keys(formErrors).length === 0) {
      console.log("Form Submitted");
    } else {
      console.log("Failed");
    }
}

At first render, the value of Object.keys(formErrors).length is 0, but the errors are shown on the screen, weird!.

I tried to use useRef which worked, but it doesn't display the errors on screen because the component doesn't rerender with useRef.

How do I prevent this form from being submitted if errors still exist?

Thank You

CodePudding user response:

Your problem is that you have called set state (formErrors) and then you try to read it immediately. So when you set it, it hasn't been updated yet, you are reading stale data.

To fix it use some local variable in that function (initially you may want to initialize it with state data) to keep track of errors, and then at the end when you are done with it, put that in state.

Something like this

const registerUser = () => {

    let errors = {
        ...formErrors
    }

    if (firstName === "") {
        errors.firstName = "Firstname is required!"        
    }

    if (lastName === "") {
        errors.lastName = "lastName is required!"    
    }

    if (Object.keys(errors).length === 0) {
        console.log("Form Submitted");
    } else {
        console.log("Failed");
    }

    setFormErrors(errors)
}
  • Related