I'm completely new to state management and I've hit a roadblock. Any assistance would be greatly appreciated.
This is how my store is set up:
import Vue from "vue";
import Vuex from "vuex";
Vue.use(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;
}
Prior to accessing any route, my route-guard verifies whether the user is an 'Admin' or not and adjusts the component options accordingly.
This is how my route guard is structured:
import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);
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) {
next();
} 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;
}
Furthermore, my 'AddPost.vue' component looks like this:
<template>
<div>
<div v-if="$store.state.isAdmin">
<h1>Welcome Admin </h1>
</div>
<div v-else> Welcome Guest </div>
</div>
</template>
<script>
export default {
created(){
console.log(this.$store.state.isAdmin); //output: false
}
}
</script>
Even though the vuex-store's state successfully changes to "isAdmin:true" upon a positive server response, the component does not reflect the updated status. I'm puzzled as to what mistake I might be making. How can I resolve this issue?