How to use value which is getting changed in an async function and use that value inside that async function?

406 Views Asked by At

I am currently working on a nextjs project and task is to simply validate whether user has entered correct details or not during registration. For that purpose i am using useState hook from react and changing it's state whenever user clicks on register button.

Now, i have made an async function which gets invoked whenever user clicks on register button. After that i am checking values and changing states accordingly. If every condition is true then i am sending post request to the server to save that user. This is being done by calling addUser function. My problem is that even if my conditions are false still code inside the if block is getting executed and i think its because of the fact that states doesn't change immediately and maybe because of async function. My if block is getting old values. Here's a snap of my code.

const submitHandler = async (e) => {
    e.preventDefault();

    //Take values from inputs
    const enteredUserName = userNameRef.current.value;
    const enteredMoodleId = moodleIdRef.current.value;
    const enteredEmail = emailRef.current.value;
    const enteredPassword = passwordRef.current.value;

   

    //Show Error
    regexForMoodleId.test(enteredMoodleId)
      ? setMoodleError(false)
      : setMoodleError(true);

    regexForEmailId.test(enteredEmail)
      ? setEmailError(false)
      : setEmailError(true);

    regexForPassword.test(enteredPassword)
      ? setPasswordError(false)
      : setPasswordError(true);

    if (
      !moodleError &&
      !passwordError &&
      !emailError &&
      checkboxState
    ) {
      //Making spinner visible
      setSpinner(true);

      const response = await addUser(
        enteredUserName,
        enteredMoodleId,
        enteredEmail,
        enteredPassword
      );
      if (response.status === 201) {
        console.log(response.status);

        //Disabling spinner
        setSpinner(false);

        //Redirecting to signin page
        await router.push("/signin");
      } else if (response.status === 302) {
        console.log(response.status);
        //Disabling spinner
        setSpinner(false);
        //Opening error message
        setOpen((prevState) => {
          return {
            ...prevState,
            open: true,
            message: "User already exists! Please signin to continue.",
          };
        });
      } else {
        //Disabling spinner
        setSpinner(false);
        //Opening error message
        setOpen((prevState) => {
          return {
            ...prevState,
            open: true,
            message: "An error has been occurred. Please try again",
          };
        });
      }
    }
  };

I want a way in which i can force if block to get new values or wait until values are being updated.

1

There are 1 best solutions below

2
Drishti Jain On

If your problem is that state is not updating before the rest of the code is executed then do this in class based component:

this.setstate({var:new_value}, function(){
//rest of the code
});

Function based component equivalent is :

const [data, setData] = useState(false);

useEffect(() => {
    doSomething(); // This is be executed when the state changes
}, [data]);

setData(true);