Home > Mobile >  SetState() is not getting updated
SetState() is not getting updated

Time:12-15

I was working on simple form Validation, when I press login button. It should check all the required field whether they are empty or not ? if yes then show the error message.

Below is the code snippet.

  const [user, setUser] = useState({
    name: "",
    password: "",
    email: "",
    confirmpassword: "",
  });
  const [formErrors, setFormErrors] = useState({
    name: "",
    password: "",
    email: "",
    confirmpassword: "",
  });


onSubmit:
  const handleSubmit = (e) => {
    e.preventDefault();
    const isFormValid = validForm();
    
  };


  const validForm = () => {
    if (
      user.email.trim() === "" ||
      user.password.trim() === "" ||
      user.name.trim() === ""
    ) {
      if (user.password.trim() === "") {
        setFormErrors({
          ...formErrors,
          password: "Password Length must be between 4 and 6 characters",
        });
        
      }

      if (user.name.trim() === "") {
        setFormErrors({ ...formErrors, name: "Required Field" });
        
      }
      if (user.email.trim() === "") {
        setFormErrors({ ...formErrors, email: "Required Field" });
       
      }

      return false;
    } else {
      setFormErrors({ ...formErrors, email: "", password: "", name: "" });
      return true;
    }
  };
 {formErrors.email === "" ? null : (
          <div className="">{formErrors.email}</div>
        )}

Only email field is showing the required filled error, all are not getting updated.

Below is the snapshot of user object after clicking on login button.

{name: '', password: '', email: 'Required Field', confirmpassword: ''}

Please help on this.

CodePudding user response:

It is not working because you are trying to setState values same time, before updating so on the last line (email check) it will update the state with old values since none of the above setState is completed

I have a different method of implementation for validForm function

const validForm = () => {
    let valid = true;
    let tempFormErros = {}
      if (user.password.trim() === "") { //&& add password condition check
          tempFormErros.password = "Password Length must be between 4 and ...";
          valid = false;
      }

      if (user.name.trim() === "") {
          tempFormErros.name = "Required Field";
          valid = false;
      }
      if (user.email.trim() === "") {
        tempFormErros.email =  "Required Field";
        valid = false;
      }
      if(!valid) {
          setFormErrors(tempFormErros)
      }
      return valid;
    }
  };

CodePudding user response:

Because when the state change in name and password if clause. It ain't reflect change in email if clause try to save it in local variable for eg


const validForm=()=>{
let errorObj={}
if (user.name.trim() === "") {
        errorObj.name= "Required Field"       
      }

....
setFormErrors({...formErrors,...errorObj})

}

CodePudding user response:

setState doesnt mutate the state it repalces it with a new object and this is asynchronous function . you have to update it with the function way

setFormErrors((formErrors)=>({ ...formErrors,  password: "Password Length must be between 4 and 6 characters"}));
setFormErrors((formErrors)=>({ ...formErrors, name: "Required Field" }));
setFormErrors((formErrors)=>({ ...formErrors, email: "Required Field" }));

Check out react docs for more info hooks state react docs

  • Related