Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!