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

270
Vistas
React: How to save value from async function and use later

I have an async function that calls an api getting me the current role of a user. Later on I want to attach that role to a variable. Here's my code

const getRole = async () => {
        const response = await roleService.getRole();
        const roles = await response.role
        return roles
    }
     ...........

 const currentRole = getRole() //I want this to be the value from return roles

I'm new to react and having trouble with this. How can I set currentRole to the value in return roles?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I would opt to save the information that you got from the API on a state

const [roles, setRoles] = useState();

const getRole = async () => {
        const response = await roleService.getRole();
        const roles = await response.role
        setRoles(roles);
    }

you can call the gerRole function on a useEffect like this

useEffect(() => {
getRole();
}, []);

or you can call the getRole function on a button click

<button onClick={getRole}>Click me to get roles</button>
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