I'm trying to render user data returned from AWS Cognito but I'm unable to save the obejcts state. This is the object that is returned from Cognito:
{
"custom:type": "Donor",
"sub": "48b8b2dd-7a7c-4cbf-b14e-cf70e55a9cd8",
"address": "address1",
"email_verified": false,
"custom:abn": "12345678",
"phone_number_verified": false,
"given_name": "John",
"custom:business_name": "Name of Business",
"phone_number": " 1123456",
"family_name": "Smith",
"email": "[email protected]"
}
I am trying to store this object using the useState hook in react as shown in the code below. However, nothing seems to be stored in my attributes object. When I run console.log(attributes) in the last line it shows up as an empty object.
const [attributes, setAttributes] = useState({});
useEffect(() => {
fetchAttributes();
}, []);
const fetchAttributes = async() => {
try{
const userData = await Auth.currentAuthenticatedUser();
const attributesList = userData.attributes;
console.log(attributesList);
setAttributes(attributesList);
} catch (error) {
console.log('error in fetching user data', error);
}
};
console.log(attributes);
CodePudding user response:
At the first render, the object is empty since the retrieval of the attributes takes some times. If the attributes variable is used in the return, you should have a second render after the use of setAttributes with the filled object in the console