[Vuejs]-Vue.js vuex state not working correctly

1๐Ÿ‘

โœ…

You have the function declared in the global scope like this:

function requireAuth() { 
    return this.$store.state.isLoggedIn; 
}

So when you call this function this is bound by default to global object. But since ES6 this will be undefined instead of the global object. So you get the error cannot read $store of undefined

Since you are importing the store in app.js you can directly use:

function requireAuth() { 
    return store.state.isLoggedIn; 
}

EDIT

export the created store instance itself, not a function that returns a store instance as follows:

store.js

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const LOGIN = "LOGIN";
const LOGIN_SUCCESS = "LOGIN_SUCCESS";
const LOGOUT = "LOGOUT";

const store = new Vuex.Store({
        state: {
            isLoggedIn: !!localStorage.getItem("token"),
            user: null
        },
        mutations: {
            [LOGIN] (state) {
                state.pending = true;
            },
            [LOGIN_SUCCESS] (state) {
                state.isLoggedIn = true;
                state.pending = false;
            },
            [LOGOUT](state) {
                state.isLoggedIn = false;
            }
        },

        actions: {
            login({state, commit, rootState}) {
                commit(LOGIN_SUCCESS);
            },

            setUser({state, commit, rootState}, user) {
                //todo
            }
        }
    });


export default store;
๐Ÿ‘คVamsi Krishna

1๐Ÿ‘

The requireAuth function should be:

function requireAuth() {
    return store.state.isLoggedIn;
}

requireAuth is just a function defined in your app.js and this.$store is how you would refer to the store inside a Vue method. Instead, you can just refer to it in the function as store.

๐Ÿ‘คBert

Leave a comment