Home > Blockchain >  How to update the React State only after a return from API called is completed
How to update the React State only after a return from API called is completed

Time:06-19

basically what I want to do is to change a text that says "welcome" initially to "hello {user}, please check your email for verification" after the user has submitted a registration AND with a successful response from API that contains the above string.

However it seems the response variable is set to undefine before returning of the signup function (that posts and receives a return from an API call), and thus Setmessage is setting the message variable as undefined instead of the returned string that only comes after a few seconds later.

I have researched many methods about useEffect, call back function and AJAX knowledge, but I still don't really understand what I need to do in my code.

export default function Signup() {
        const [message, Setmessage] = useState('Welcome')
        async function handleSubmit(e){
       
            const response = await signup(usernameRef.current.value, emailRef.current.value, passwordRef.current.value)
            Setmessage(response)
        }

        return(
        {message}
        //a submission form that invokes handlesubmit
        )
}

//sign up function from another component
function signup(name, e, p){
        axios.post('/register', {
            username: name,
            email: e,
            password: p
          })
          .then(function (response) {
            console.log(response.data[0])
            return response.data[0];//"dear user, please check etc..."
          })
    }

//api using Fastapi
@app.post("/register")
async def user_register(user: UserIn_Pydantic):
    user_info = user.dict(exclude_unset=True) #user changed into dictionary format
    user_info["password"] = get_password_hash(user_info["password"]) #we create new password field and save hashed password in
    #exclude_unset: whether fields which were not explicitly set when creating the model should be excluded from the returned dictionary
    user_obj = await User.create(**user_info) #stores it in database table user
    new_user = await user_pydantic.from_tortoise_orm(user_obj)#convert userobj into pydantic model
    await simple_send(email=[new_user.email], instance=new_user)

    

    return {
        "{}, please check you email for verification link, {}".format(new_user.username,new_user.password)
    }

CodePudding user response:

The await operator is used to wait for a Promise.

So in order to await signup() in handleSubmit, the signup function itself needs to return a promise. eg

function signup(name, e, p) {
  return axios
    .post("/register", {
      username: name,
      email: e,
      password: p,
    })
    .then(function (response) {
      console.log(response.data[0]);
      return response.data[0]; //"dear user, please check etc..."
    });
}
  • Related