Home > Mobile >  Unexpected behavior with my native react input validation
Unexpected behavior with my native react input validation

Time:09-13

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'.

CodePudding user response:

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');
  }
}
  • Related