[英]How to display group of a user authenticated using Cognito using React?
I have a app running on amplify which is authenticated using Cognito.我有一个在 amplify 上运行的应用程序,它使用 Cognito 进行了身份验证。 I am trying to display the user's group (render).
我正在尝试显示用户的组(渲染)。 I have the following code to get the user's information.
我有以下代码来获取用户的信息。
export const getCurrentUser = async () => {
try {
const userInfo = await Auth.currentAuthenticatedUser({bypassCache:true})
console.log("User info: ",userInfo)
if(userInfo){
return userInfo.signInUserSession.idToken.payload["cognito:groups"];
}
}
catch (err) {
console.log('error: ', err)
}
}
And then the app function然后是应用程序 function
function App() {
return (
<Authenticator formFields={formFields} components={components}>
{({ signOut, user }) => (
<div className="App">
<p>
--> This does not work
Hey {user.username}, Welcome to NUBER. You are a {getCurrentUser()[0]}
</p>
<button onClick={signOut}>Sign out</button>
</div>
)}
</Authenticator>
);
}
export default App;
How can I render the user's group to the screen?如何将用户组呈现到屏幕上?
Your getCurrentUser function is an async/await promise so you need to handle the output asynchronously.您的 getCurrentUser function 是异步/等待 promise 因此您需要异步处理 output。
Here's an example:这是一个例子:
function App() {
const [groups, setGroups] = useState([]);
useEffect(() => {
const getGroups = async () => {
const groups = await getCurrentUser();
setGroups(groups);
}
// make sure to catch any error
getGroups().catch(console.error);
});
return (
<Authenticator formFields={formFields} components={components}>
{({ signOut, user }) => (
<div className="App">
<p>
Hey {user.username}, Welcome to NUBER. You are a {groups[0]}
</p>
<button onClick={signOut}>Sign out</button>
</div>
)}
</Authenticator>
);
}
export default App;
Just keep in mind that you need to handle async operations inside use effects differently.请记住,您需要以不同的方式处理使用效果中的异步操作。 Here's a post about it, but there are many others online.
这是一篇关于它的帖子,但网上还有很多其他的。
https://devtrium.com/posts/async-functions-useeffect https://devtrium.com/posts/async-functions-useeffect
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.