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

186
Visualizações
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 Respostas
Responde à pergunta

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 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