Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

119
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda