1

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?

ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • Please see [How do I return the response from an aynchronous call](https://stackoverflow.com/q/14220321/438992), which this duplicates. – Dave Newton Aug 05 '22 at 16:22
  • Since you're in react, the most likely thing you'll do once you have the value is set state. So perhaps instead of `return roles` you'll do `setRoles(roles)` – Nicholas Tower Aug 05 '22 at 16:23
  • const response = await roleService.getRole(); return response.role – Dhinesh Aug 05 '22 at 16:23

1 Answers1

2

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>