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

183
Vistas
Use value from axios function in another function

I have this async function to get an API access token:

const getAccessToken = async () => {
    try {
        const body = new URLSearchParams({
            grant_type: 'client_credentials',
            scope: 'manage:all'
        }).toString();

        const config = {
            headers: {
                Content_Type: 'application/x-www-form-urlencoded'
            },
            auth: {
                username: clientId,
                password: clientSecret
            }
        };

        const { data: res } = await axios.post(
            `${baseUrl}/oauth2/token`,
            body,
            config
        );

        return res;
    } catch (err) {
        console.log(err);
    }
};

It return a promise which I use in the following function to log the access token to the console:

getAccessToken().then(res => {
    console.log(res.access_token);
});

It logs the token as a string.

Now I want to use this string value in another function in my code. Do I just call the function where I need the value like above and replace the console.log with return?

How do I use this string value in other parts of my code?

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

0

One way of doing it to call the function everywhere,

async function anotherFunction() { 
    const res = await getAccessToken();
    console.log(res.access_token)
}

Another way of doing this is to call the function on your page load save the token in session/local storage/cookies and use the token in other functions by fetching it from session/local storage/cookies to avoid making multiple API calls.

On page load

const res = await getAccessToken();
localStorage.setItem('token', res.access_token);


async function anotherFunction() { 
    const res = localStorage.getItem('token');;
    console.log(res.access_token)
}
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