[Vuejs]-Wrap a Vue.js Firebase-Object into onAuthStateChanged handler?

0👍

The problem maybe with how you configured and initialized firebase.

Its better to use progressive enhancement, so you can access the services you need when you need them.

Change your firebase.js config file to the following

// Firebase App (the core Firebase SDK) is always required and
// must be listed before other Firebase SDKs
import * as firebase from "firebase/app";

// Add the firebase services that you want to use
import "firebase/database";
import "firebase/auth";

// Initialize firebase
const firebaseConfig = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
};

const fb = firebase.initializeApp(firebaseConfig);
const db = firebase.database();

// export firebase services
export { db, fb };

Next change your main.js to the following

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import { fb } from "firebase"; // your firebase services live here (auth)
require("firebase/database"); // !important

import { rtdbPlugin } from 'vuefire'
Vue.use(rtdbPlugin);

Vue.config.productionTip = false;

let app = '';

firebase.auth().onAuthStateChanged(() =>{
  if(!app){
    app = new Vue({
      router,
      render: h => h(App)
    }).$mount("#app");
  }
});

Next change your route guarding logic in your router file to the following

import { fb } from "../firebase.js";
const router = new VueRouter({
  routes
});

// check if route requiresAuth
router.beforeEach((to, from, next) => {
  if (to.matched.some(rec => rec.meta.requiresAuth)) {
    const user = fb.auth().currentUser;
    // check auth state of user
    if (user) {
      next(); // user signed in, proceed to route
    } else {
      next('/login'); // user not signed in, route to login
    }
  } else {
    next(); // route does not require auth
  }
});

export default router;

Finally you should be able access to access the uid like so

firebase: {
    tableTennisData: db.ref(fb.auth().currentUser.uid).child('tableTennis'),
}

Remember fb now contains your firebase services and db now refers to your chose database (firestore/rtdb).

So you would access you firebase services like so

fb.auth()
fb.storage()
fb.analytics()

And you would access you rtdb like so

db.ref.('/users/' + uid)

Hopes this helps.

Leave a comment