marcelo.delta
marcelo.delta

Reputation: 3082

Problem importing getters into Router - Vuex

Problem importing getters into Rotate - Vuex.

I am trying to import a value that is within the vuex state.

An error is reported, stating that it is undefined.

I have no idea what I might have done wrong. Please, if anyone can help, I will be very grateful.

Thanks for listening

Error TypeError: "_store__WEBPACK_IMPORTED_MODULE_4__.default.getters is undefined"

Store

import Vue from 'vue'
import Vuex from 'vuex'
import auth from './module-auth'

Vue.use(Vuex)
export default function () {
  const Store = new Vuex.Store({
    modules: {
      auth
    },
    strict: process.env.DEV
  })
  return Store
}

module-auth Getters

import decode from 'jwt-decode'

function isTokenExpired (state) {
  try {
    const decoded = decode(state.token)
    if (decoded.exp < Date.now() / 1000) {
      return true
    } else return false
  } catch (err) {
    return false
  }
}
export {
  isTokenExpired,
}

Router

import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '../store'

Vue.use(VueRouter)

export default function () {
  const Router = new VueRouter({
    scrollBehavior: () => ({ x: 0, y: 0 }),
    routes,
    mode: process.env.VUE_ROUTER_MODE,
    base: process.env.VUE_ROUTER_BASE
  })

  Router.beforeEach((to, from, next) => {
    const publicPages = ['/']
    const authRequired = !publicPages.includes(to.path)

    const loggedIn = store.getters['auth/isTokenExpired']
    console.log(loggedIn)

    if (authRequired && !loggedIn) {
      return next('/')
    }
    next()
  })
  return Router
}

Upvotes: 0

Views: 634

Answers (2)

Slim
Slim

Reputation: 1276

Exporting a function that create a store and use it as a function will create many stores and is not desired.

Since you need to use one instance of store anywhere, you need to export the store instance, not a function that create a store.

Upvotes: 1

Ivan Klochkov
Ivan Klochkov

Reputation: 702

Your mistake is that you try to use a function as Vuex module. Module should be an object. Docs say:

export const moduleA = {
  state: { count: 0 },
  mutations: {
    increment(state) {
      state.count++;
    }
  },

  getters: {
    doubleCount(state) {
      return state.count * 2;
    }
  }
};

And your function isTokenExpired looks like it should be placed in "getters" section.

Upvotes: 1

Related Questions