0

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 Answers 2

0

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
 }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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;
    } 
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.