[英]React doesn't recognize user attributes in Amplify app
I built an Amplify app with Cognito user pools for authentication/authorization.我使用 Cognito 用户池构建了一个 Amplify 应用程序以进行身份验证/授权。 I am now trying to retrieve user attributes using
Auth.currentAuthenticatedUser()
.我现在正在尝试使用
Auth.currentAuthenticatedUser()
检索用户属性。 The example code they have (which works well) is the following:他们的示例代码(效果很好)如下:
import { Auth } from 'aws-amplify';
Auth.currentAuthenticatedUser({
bypassCache: false
})
.then((user) => console.log(user))
.catch((err) => console.log(err));
Here, the console.log(user)
logs all of the current user data, as expected.在这里,
console.log(user)
按照预期记录了所有当前用户数据。 I would like to now capture that data (or at least individual attributes of it) in a variable that I can use later on.我现在想在我以后可以使用的变量中捕获该数据(或至少它的单个属性)。 However, if I try to define a variable using
user
it gives me an undefined error.但是,如果我尝试使用
user
定义一个变量,它会给我一个未定义的错误。
Here is an example of what I have tried and the error generated:这是我尝试过的示例以及生成的错误:
Code:代码:
Auth.currentAuthenticatedUser({
bypassCache: false
})
.then((user) => console.log(user))
.catch((err) => console.log(err));
let userData = user;
Error:错误:
'user' is not defined no-undef
I have also tried const
and var
but no matter what, it does not recognize user
.我也尝试过
const
和var
但无论如何,它都无法识别user
。 I don't understand how this is possible since it is successfully logged two lines above.我不明白这是怎么可能的,因为它已成功记录在上面的两行中。 Any ideas would be appreciated!
任何想法,将不胜感激!
I was able to store the values within a const
by putting it inside of a try/catch block:通过将值放在 try/catch 块中,我能够将值存储在
const
中:
try {
const user = await Auth.currentAuthenticatedUser();
const userGroup = user;
console.log(user);
} catch (err) {}
In my case, I only wanted the user group, so I actually narrowed it down to that parameter:在我的例子中,我只想要用户组,所以我实际上将它缩小到那个参数:
const userGroup = user.signInUserSession.accessToken.payload["cognito:groups"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.