[Vuejs]-Am trying to redirect the user but the this.$router.push('/') is giving me undefined

0👍

You are accessing this within the onAuthStateChanged function scope, which means this inside the scope will refers to the own function (since you are using arrow function), not Vue instance.

This wont work:

handleAuthStateChanged: ({ commit }) => {
    auth.onAuthStateChanged(user => {
        ...
        // `this` is not a Vue instance
        this.$router.push("/");
    })
}

You need to make a variable that refer to Vue instance first outside the scope so you can call it inside the function scope, for example:

handleAuthStateChanged: ({ commit }) => {
    const self = this;
    auth.onAuthStateChanged(user => {
        ...
        // `this` is not a Vue instance, but `self` is
        self.$router.push("/");
    })
}

Or don’t use arrow function since this inside an arrow function refers to the function it self, for example:

handleAuthStateChanged: ({ commit }) => {
    auth.onAuthStateChanged(function(user) {
        ...
        // `this` is a Vue instance 
        this.$router.push("/");
    })
}

Leave a comment