Watch Changes in Vue Observable

Viewed 1210

I am trying to implement a method to check a users login status based on firebase's firebase.auth().onAuthStateChanged(). I would like to use this across my app as a global variable.

At the moment, I am using a Vue.observable store to set the value of my signed in state.

store.js

export const store = Vue.observable({
  signedIn: false,
});

export const mutations = {
  setSignedIn(bool) {
    store.signedIn = bool;
  },
};

At the start of my app, I then call the check auth function App.vue

   import {mutations} from './store'
   this.$firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        mutations.setSignedIn(true);
      } else {
        mutations.setSignedIn(false);
      }
    });

Finally, within one of my child components I check the store to see the signedIn status. Based on that, I will either use the chrome.storage if not signed in, or firebase if signed in.

List.js

     import {store} from './store'
      if (store.signedIn) {
        // use firebase
      } else {
       // use chrome storage
      }

My main issue is that the firebase.auth().onAuthStateChanged() function is asynchronous thus my store.signedIn value is always false and it does not update when it changes.

My goal is to wait until the onAuthStateChanged is done and check the store.signedIn but my attempts have not worked so far.

1 Answers

Make a computed property called isSignedIn then watch it using watch option :

import {store} from './store'

export default{

 ...
computed:{
   isSignedIn(){
         return store.signedIn;
        }
},
watch:{
   isSignedIn(newVal,oldVal){
    if (newVal) {
        // use firebase
      } else {
       // use chrome storage
      }
 }
}
}
Related