Reputation: 19
I am using firebase authentication with vue application Every time I restart the page after I log in a user currentUser turns to null
firebase.auth().signInWithEmailAndPassword(this.email, this.password)
.then(() => this.$router.push({name: 'Home'}))
.catch(err => this.feedback = err.message)
and in vue router
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
let user = firebase.auth().currentUser
if (!user) {
next({name: 'Login'})
} else next()
} else next()
})
I want the user to sign in once not every time the page restarts
Upvotes: 2
Views: 539
Reputation: 7548
This is caused because beforeEach
is getting executed before firebase has fully finished initialization.
You can use onAuthStateChanged
observer to make sure the vue app is initialized only after the firebase is fully initialized.
One way to fix it is to wrap the vue initialization code in main.js(new Vue( ... )
) with onAuthStateChanged
like this:
let app;
...
firebase.initializeApp( ... );
firebase.auth().onAuthStateChanged(() => {
if (!app) { // ignore reinitializing if already init (when signing out/login)
new Vue( ... )
...
}
})
Upvotes: 2