Vuex Get State After Mutation in components

I am very new to state management and I got stuck in one position. Any help will be highly appreciated.

I have my store setup as:

import Vue from "vue";
import Vuex from "vuex";


export default function() {
  const Store = new Vuex.Store({
    modules: {},

state: {
      isAdmin: false,

mutations: {
      changeAuthStatus(state, authStatus) {
        state.isAdmin = authStatus;
        console.log(state.isAdmin) //output: true
actions: {
      changeAuthStatus({ commit }, authStatus) {
        commit("changeAuthStatus", authStatus);

  return Store;

Before Entering to any route my route-guard will check if the user is 'Admin' or not and display the options in component accordingly.

My route guard is setup as:

import Vue from "vue";
import VueRouter from "vue-router";


import $store from "../store/index";
const store = $store();

let adminStatus = store.state.isAdmin;

const requireAuth = (to, from, next) => {
    adminStatus = true;
    store.dispatch("changeAuthStatus", authStatus);  
  if (adminStatus) {
  } else next({ name: "Home" });

const routes=[
    path: "/",
    name: "Home",
    component: () => import("components/Home.vue")
    path: "/add/",
    name: "AddPost",
    beforeEnter: requireAuth,
    component: () => import("components/AddPost.vue")

export default function(){
const Router = new VueRouter({routes});

  return Router;

And my 'AddPost.vue' component is setup as:

    <div v-if="$store.state.isAdmin">
    <h1>Welcome Admin </h1>
    <div v-else> Welcome Guest </div>

export default {
   console.log(this.$store.state.isAdmin); //output: false

On a positive response from server the state in vuex-store is mutating successfully to "isAdmin:true" but the component is not getting the updated status. I don't know what I am doing wrong. How can I solve this please?

2 answers

  • answered 2021-01-11 06:15 Yash Maheshwari

    You can define a getter in the store which will return the state of isAdmin and then use the getter to fetch the value in your component from the store.

  • answered 2021-01-11 07:03 Dan

    Export a store object instead of a function. Otherwise the store that you pass to the Vue app in main.js (providing it to components) will not be the same store that you use in your route guard.

    export default new Vuex.Store({
      state: {},
      getters: {},
      mutations: {},
      actions: {},
      strict: true