[英]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.我有一个异步 function 调用 api 让我获得用户的当前角色。 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
?如何将currentRole
设置为return roles
的值?
I would opt to save the information that you got from the API on a state我会选择将您从 API 获得的信息保存在 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 上调用 gerRole function
useEffect(() => {
getRole();
}, []);
or you can call the getRole function on a button click或者您可以单击按钮调用 getRole function
<button onClick={getRole}>Click me to get roles</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.