How to detect the user's firebase authentication login status in a vue js project?

2.5k Views Asked by At

I am trying to detect the userstate. If the user is logged in I want to set the data "userstate" to true. I am using vuefire and firebase into my vue project. I tried the way shown below, but it does not work

 data() {
    return {
        userstate:false
    };
  },


watch:{
    userstate:{
    firebase.auth().onAuthStateChanged(function(user){
        if(user){
        this.userstate= true;}
        else{
        this.userstate=false;
        }
        })}
2

There are 2 best solutions below

0
On

In Firebase you can check whether the user is signed in or not by using a function provided by the firebase which is auth().currentUser

// user will return true which means user EXISTS!
let user = firebase.auth().currentUser; 

if (user) {  
  this.userstate = true; // If it exists
} else { 
 this.userstate = false; // If it doesn't
} 

There are cases when the above mentioned method returns null / undefined for the user. So this solution is for your existing solution. So in that case try modifying your existing function to this:

async function IsLoggedIn() {
try {
 await new Promise((resolve, reject) =>
  firbase.auth().onAuthStateChanged(
    user => {
      if (user) {
        // Yes User is signed in.
        resolve('User is there');
      } else {
        // No user is not signed in.
        reject('There is no user');
      }
    },
    // Prevent console errors
    error => reject(error)
  )
)
return true
} catch (error) {
  return false
 }
}
0
On

Also since you intend to watch for the auth state change you can simply register the listener right after you initialize Firebase, you do not necessarily have to insert it in a VueJS watch block, you can insert it in your main.js for example, and if you are using a store like VueX you can update the state in the store and pull that information from any component of the VueX application.

firebase.initializeApp(configOptions);

firebase.auth().onAuthStateChanged(user => {
    if (user) {  
        this.userstate = true;
    } else { 
        this.userstate = false;
    } 
});