AWS Amplify, await Auth.currentUserInfo

Viewed 1093

I need to get some custom attributes from Cognito, and to do something with that info.

I have this function:

const getMyAttribute = async (): string => {
  const userInfo = await Auth.currentUserInfo();
  console.log('userInfo', userInfo);
  return userInfo.attributes['custom:myAttribute']
};

And I'm calling it here in some React Component with:

const myAttribute = getMyAttribute();
console.log('myAttribute:', myAttribute); // Here is weird output
// Here I need to do something with `myAttribute`

In console.log I'm getting this:

myAttribute:  {"_40": 0, "_55": null, "_65": 0, "_72": null}

userInfo: {"attributes": {"custom:myAttribute": "6", "email": "testpending4@test.cl", "sub": "etc..."}, ... rest of user info data from Cognito}

So, I'm getting some weird output in myAttribute at calling the function, but the real data from Cognito comes later on userInfo

How can I get the real data on myAttribute as well?

2 Answers

At your call site for getMyAttribute() it looks like you're missing an async keyword.

Does changing the line const myAttribute = getMyAttribute(); to const myAttribute = async getMyAttribute(); improve the output?

From your code, getMyAttribute is promise method. That's why you get asynchronize process when call it. To call it properly, you must work with async - await and you have done with other issue. Other way, have you tried this ?

let myAttribute;
getMyAttribute().then(attribute => {
    myAttribute = attribute;
})
Related