I am working on an Angular project where I am authenticating my user and I want to get the current authenticated user which works fine. I set the component user property in NgOnInit() but then I try to access the property in another function and it undefined there even though I have assigned it a value of the authenticated user. Why is that and how do I prevent it from happening?
Here is my code:
NgOnInit() {
this.setCurrentUser();
this.getData();
}
setCurrentUser() {
Auth.currentAuthenticatedUser().then(user=> {
console.log(user);
this.currentUser = user;
})
}
getData = () => {
console.log("DATA USER:")
console.log(this.user)
}
It is happening because of aync function Auth.currentAuthenticatedUser(). you can use async...await or call the getData() in then()
then approach
setCurrentUser() {
Auth.currentAuthenticatedUser().then(user=> {
console.log(user);
this.currentUser = user;
this.getData();
})
}
Async...await approach
async NgOnInit() {
await this.setCurrentUser();
this.getData();
}
setCurrentUser() {
return Auth.currentAuthenticatedUser().then(user=> {
console.log(user);
this.currentUser = user;
})
}
getData = () => {
console.log("DATA USER:")
console.log(this.user)
}