I'm using Amplify for Angular for user authentication, and I am building a small menu for the user profile. I want to retrieve the current user info and display the user's email in the menu button. However the DOM doesn't update after retrieving the user data from the Amplify Auth API, even after confirming that the data is coming in successfully.
HTML:
<button mat-icon-button #profile [matMenuTriggerFor]="menu">
<mat-icon>account_circle</mat-icon>
</button>
<label class="user" for="profile">{{ user?.attributes.email }}</label>
TS (note that this.user
is successfully logged to console successfully after fetching the data):
async ngOnInit() {
await Auth.currentUserInfo()
.then((data) => {
this.user = data;
console.log(this.user); // This successfully prints the user data
})
.catch((err) => {
console.log(err);
});
}
And then to add to the weirdness, if you click the menu button, the DOM will somehow finally update to make the user data visible. Screen recording here: https://i.imgur.com/nRAnfax.mp4
Why isn't the DOM updating immediately after fetching the user data? And why does this only seem to happen when retrieving data from Amplify?
You may be outside the "zone" Try to run your code in an NgZone You can also call manually the changedetector mechanism
A 3rd option is to make use of observables (and use | async
in the DOM)
Also your then
and your await
are redundant
try {
this.user = await Auth.currentUserInfo();
} catch(err) {
console.log(err);
}
Or
Auth.currentUserInfo()
.then((data) => {
this.user = data;
console.log(this.user); // This successfully prints the user data
})
.catch((err) => {
console.log(err);
});