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

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

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