Trying to get the status of firebase user authentication

Viewed 76

I have an authentication function using firebase which is just the auth code from the firebase documentation

export const signIn = (email,password) => {
   firebase.auth().signInWithEmailAndPassword(email, password).then(()=>{
       alert('Sign in Successful!')
    }).catch(function(error) {
        alert(error.message)
    });
}

I call it like this

signIn(mail, password)

When I call it in my code, It works perfectly and the proper alerts appear. However, I want to actually receive something from my authentication function, like True or False if the user successfully logged in or not. Is there a way for me to receive this value from my function or any workarounds?

//evaluates to True if logged in successfully and vice versa
let authState = signIn(this.mail, this.password)
2 Answers

There's a couple approaches you could take with this, the first that comes to mind is the following:

export const signIn = (email, password) => {
  return firebase.auth().signInWithEmailAndPassword(email, password).then(userCredential => {
    alert('Sign in Successful!');
    return true;
  }).catch(error => {
    alert(error.message);
    return false;
  });
}

// ......

let authState = await signIn(this.mail, this.password);

In promises you're able to return values from the .then() or .catch() method and then use that resolved value further in your code.

If you want to know when a user is signed in, no matter how they were signed in, you should instead use an auth state observer to set up a callback that will be invoked whenever the user becomes signed in or out, as shown in the documentation:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // User is signed out.
  }
});
Related