Home > Net >  Firebase auth not working on before mount hook and I don't know why
Firebase auth not working on before mount hook and I don't know why

Time:04-01

I'm using firebase for the first time and stuck on this error that I can't fix.

Basically I have a home screen and a login screen. When I run onBeforeMount to check if a user is logged in or not I'm getting the following errors:

Uncaught ReferenceError: onAuthStateChanged is not defined
at eval (webpack-internal:///./node_modules/babel-loader/lib/index.js??clonedRuleSet-40.use[0]!./node_modules/vue-loader/dist/index.js??ruleSet[0].use[0]!./src/App.vue?vue&type=script&lang=js:12:7)
at callWithErrorHandling (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:357:18)
at callWithAsyncErrorHandling (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:367:17)
at Array.hook.__weh.hook.__weh (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:3388:19)
at invokeArrayFns (webpack-internal:///./node_modules/@vue/shared/dist/shared.esm-bundler.js:648:11)
at ReactiveEffect.componentUpdateFn [as fn] (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:6089:70)
at ReactiveEffect.run (webpack-internal:///./node_modules/@vue/reactivity/dist/reactivity.esm-bundler.js:237:19)
at setupRenderEffect (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:6294:5)
at mountComponent (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:6029:5)
at processComponent (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:5979:9)

Here is what is in my main.js file:

import { createApp } from 'vue'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import { initializeApp } from "firebase/app";

const firebaseConfig = {
  apiKey: "Censored",
  authDomain: "Censored",
  projectId: "Censored",
  storageBucket: "Censored",
  messagingSenderId: "Censored",
  appId: "Censored"
};

const app = initializeApp(firebaseConfig);

createApp(App).use(router).mount('#app')

And here is the script in my app.vue file

<script>
import { onBeforeMount } from "vue";
import router from "@/router";
import { getAuth } from "firebase/auth";

export default {
  setup() {
    onBeforeMount(() => {
      const auth = getAuth();

      onAuthStateChanged(auth, (user) => {
        if (!user) {
          router.replace("/login");
        } else if (route.path == "/login" || route.path == "/signup") {
          router.replace("/");
        }
      });
    });
  },
};
</script>

CodePudding user response:

onAuthStateChanged need to be imported to

import { getAuth, onAuthStateChanged } from "firebase/auth"

  • Related