Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

123
Visualizações
How to update the React State only after a return from API called is completed

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)
    }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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..."
    });
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda