Wait for Firebase signInWithEmailAndPassword response

I am signing in a user with Firebase’s signInWithEmailAndPassword() and then get that users information with var fbuser = this.afAuth.auth.currentUser;. However, the call is asynchronous, so in order for fbuser to contain the newly submitted information, I have to call a wait function for 5 seconds to allow enough time for the user to be assigned the current user. This is obviously an awful way to do this but I can’t find anything on how to wait for fbuser to be valid. Any help would be great, thanks.

Here is the my login.ts: https://github.com/CSFoodRescueCapstone/foodfinder/blob/master/src/pages/login/login.ts

1 Like

There are a few things to point out from your repo .

I would change

user = {} as User;


user: User;

Or just eliminate it from the page altogether. Importing it from your interfaces is enough for the component to recognize it and use it as a Type in your login function.

Your login function doesn’t need this.wait(5000)

Firebase Auth returns a promise that contains the “user” (user information), if successful, or an error if not successful. So you can work off of that fact, and take specific actions based on whether or not a user is returned.
For example,

login(user: User){
this.afAuth.auth.signInWithEmailAndPassword(user.email, user.password)
.then((returnedUser) => {
       console.log('uid', returnedUser.uid);
.catch((err) => {         
       console.log('Error', err);

In this example, .then((returnedUser) =>
returnedUser IS this.afAuth.auth.currentUser
So there’s no need to assign it later.

I reformatted your example a little bit to remove the word ‘function’ from it. That’s an important one.

1 Like

Thanks so much! And for the quick reply. For some reason using only user = {} as User; satisfies the compiler when talking to my html page. But, the rest works perfectly-I tried this before but was having a hard time using returnedUser for anything except printing to the console. Maybe that was because I was including the word function. Thanks again.

Ah, sorry. I didn’t even look at the HTML. Your approach is working, and that’s good!

Happy I could help with the rest

1 Like

If you’re interested in following up on the HTML issue, try adding this to your login.ts
Still replace
user = {} as User
user: User;
And in your constructor, initialize user with empty values

constructor() {
 this.user = {
    email: "";
    password: "";
    confirmpassword: "";
    username: "";
    name: "";

I didn’t have a close enough look to see how your process of assigning to this.user works entirely, but if this works for you it’s a better fit for best-practices