Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unexpected behavior with my native react input validation

I created an input field which am trying to validate

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

                           <p>Name</p>
                          <input
                             placeholder="Name"
 
                             value={name}
                             onChange={(e) => setName(e.target.value)}
                          />

                       <Error> {formErrors.name}</Error>
                
                 <Button
                    onClick={handleSubmit}
                 >
                  Submit
                 </Button>

OnClick of the submit button it checks if the name field is empty in the handleSubmit function

   const validate = (values) => {
     const errors = {};
     if (!values.name) {
        errors.name = 'Name is required!';
     }
     return errors;
  };

  const handleSubmit = async (e) => {
        const val = {name};
        setFormErrors(validate(val));

         if (Object.keys(formErrors).length === 0) {
            console.log('No empty');
         }else{
             console.log('Empty');
         }

    };

The issue am having is that it lags behind in response. For example if the name field is empty it console’s Not empty, on first click of the buttton, if I then click the button again it then console’s the correct data which is ‘Empty’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is becasue the state is not set until the component is being re-render therefore the formErrors state is {} until the handle function ends. Create a new constant to hold the errors and use these to console the outcome instead of the state itself if you still need to do something during the event, however use the state inside the JSX to render correctly since state will have been changed by then.

const handleSubmit = async (e)=>{
  const val = {name};
  const errors = validate(val)
  setFormErrors(errors);      
  if (Object.keys(errors).length === 0) {
    console.log('No empty');
  }else{
    console.log('Empty');
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading