Accessing Vuex State After Mutation in Components

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?

Answer №1

Ensure to export a store object, rather than just a function. This is important because if you pass the store to your Vue app in main.js for components, it may not be the same store used in your route guard.

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

Answer №2

One approach is to create a getter within the store that retrieves the current status of isAdmin. This getter can then be utilized in your component to access and display the value obtained from the store.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you use mouseover events to display a popover and manipulate the div id?

In my scenario, I have multiple div elements and I want to display separate popover for each div. Initially, the popover is not shown on the first mouseover event but works perfectly on subsequent attempts. Below is the code snippet: $(document).read ...

Creating an interactive button using RichFaces and Bootstrap for seamless Ajax functionality

I have a challenge with making a fully clickable span or button that includes a Bootstrap refresh glyph-icon. The current code I have inherited only allows the icon itself to be clicked, leaving the area between the icon and button border unclickable. This ...

Ways to initiate JavaScript event upon clearing input form field

I'm working on creating a dynamic search feature. As the user types in the search box, JavaScript is triggered to hide the blog posts (#home) and display search results instead (the specific script for this is not shown below). However, when the user ...

Is there a way to convince Python to interpret data as a multi-dimensional list instead of a string when converting from HTML?

Currently, I am working on formatting table data in HTML and then sending it to Python using the script below: var html_table_data = ""; var bRowStarted = true; var count1 = 1 $('#woTable tbody>tr').each(function () { if (count1 != 1) { ...

Trouble with Establishing Fresh Routes in Express.js

I am currently using express.js to develop an application with two ejs pages that are accessible through navigation. However, I am looking to expand the functionality of my app by incorporating more ejs (pug) pages to make it more dynamic. I want to update ...

Tips for utilizing the date-formatter feature of bootstrap-table with Angular 2

Hello there! I have integrated the bootstrap-table library with Angular4, but I am facing an issue with the date-formatter feature. Here is the HTML code snippet: <table id="table" data-show-refresh="true" data-show-toggle="true" data-show-columns="tr ...

Show the flex items arranged horizontally

This template is generated dynamically by Django: <div class="center row"> <h3><span>The Core</span></h3> {% for member in core %} <a class="core_img " href="#"> <div class="img__overlay"> ...

Referencing a JSON object

Here is a JSON list of search terms: [ "halo", [ "halo reach", "halo anniversary", "halo 4", "halo 3", "halo mega bloks", "halo 2", "halo sleepsack", "halo wars", "halo reach xbox 360", "halo combat evolved" ], ...

What is the process for including a new button in the infowindow attached to a marker?

This is a JavaScript code snippet that initializes a map using the Google Maps API. It creates a marker at Uluru in Australia and opens an info window with some content when the marker is clicked. function initMap() { var uluru = {lat: -25.363, lng: 131 ...

How can a variable that is potentially undefined be converted to lowercase in Node.js?

My latest project involves developing a discord.js bot with commands that can take different parameters like mc!start vanilla, mc!start tekkit. However, the bot is designed to handle only singular string entries. So, when a user inputs just mc!start with ...

Insert a new <tr> element into a dynamic table using PHP and jQuery without the need to refresh the page

I am attempting to dynamically insert a row into an existing table when a button is clicked. The rows in the table are created dynamically based on data retrieved from a PHP script. My approach involves making an ajax call to the insert_tr.php script, whi ...

`Issues encountered with AJAX POST request in Flask-based web application`

Having issues with an AJAX POST request on my Flask web application. Specifically, I'm working on a signup page and when I click the submit button, nothing happens. There are no XHR entries in the network tab or console entries in the browser's d ...

Incorporating Bootstrap 4 into NuxtJS

I'm currently integrating Bootstrap 4 (bootstrap-vue) with Nuxt and facing some challenges. I am having trouble utilizing mixins and variables in pages or components, even after including the style-resources-module. Below is a snippet of my nuxt.con ...

Creating a pie chart with ExtJS using data from a JSON file

After successfully creating a pie chart using ExtJS with JSON values through AJAX calling, I encountered an issue when trying to do the same with JSON values retrieved from a file named myjson.json. Can anyone advise me on how to draw a pie chart by retrie ...

Using Webpack to Create a Vue Component

I'm feeling a bit foggy-headed here. I'm trying to display a simple Vue Component using Webpack. However, when I compile the code and configuration below, all I get is a <hello></hello> being rendered. The issue seems to be coming fr ...

Issue with displaying YouTube videos in HTML causing them to be downloaded instead of playing

I'm currently facing an issue with loading a video on my HTML page using the following code: <video v-for="(data, key) in projectData.videos" :key="key" width="320" height="240" controls> <source :src="data.url"> </video> One ...

Displaying unique input values with ng-model

Within the controller, there is a variable that monitors the page index (starting at 0) for a paginated table: var page { pageNumber: 0; } Query: How can I display this pageNumber variable in the HTML, but always incremented by +1? (since the index=0 p ...

In React, components will consistently render the initial code

I have a chat application that requires authentication and uses cookies. Here's what I've been attempting: class AppHeader extends React.Component { constructor(props) { super(props) } render() { if (cookies.get(' ...

Issue with Electron application encountered during relocation of build directory

Currently, I am developing an Electron-App using NPM that functions as an installer by unzipping a file to a specified directory. While everything works smoothly when I build the application and run it from the win-unpacked folder, moving the folder to a d ...

How can I incorporate a personalized checkbox into a column within a React material table?

I'm currently working on a React project where I am using a Material Table. I am trying to figure out how to add a checkbox in a table cell, for example, in the Birth year column instead of just having the year displayed. Can anyone provide guidance o ...