Accessing store in Vue, the getter function returns a value representing whether the user is currently logged

I have the user state stored in my Vue store, but when I try to access it like this:

let isLoggedIn = store.getters.isLoggedIn

Instead of getting a simple true or false, I see this in the console:

ƒ isLoggedIn (state) { return state.user ? true : false; }

This is my store code:

let store = {
    state: {
        user: '',
    },
    mutations: {
        setAuthUser(state, user) {
            state.user = user;
        }
    },
    getters: {
        isLoggedIn(state) {
            return state.user ? true : false
        }
    }
};

export default store;

In my app.js, where I call the getter:

router.beforeEach((to, from, next) => {
  let isLoggedIn = store.getters.isLoggedIn
  console.log(isLoggedIn)
  if (to.matched.some(record => record.meta.requiresAuth)) {
    
    // This route requires auth, so check if user is logged in.
    // If not, redirect to login page.

    if (!isLoggedIn) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next() // Always call next()!
  }
})

Answer №1

The issue you're experiencing is due to not properly initializing the store in your code. Instead of exporting a Vuex.Store, your store code is currently just exporting a plain object.

To correctly initialize the store, follow these steps:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

let store = /* ... */

export default new Vuex.Store(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

Analyzing file data while uploading the file

Does anyone have a solution for extracting the content from an uploaded file in express/nodejs without saving it as a temporary file? I have code that successfully pipes the input to a filestream, but I'm struggling to deserialize the upload to a pla ...

Add a container element resembling a div inside a table without implementing the table layout

I am working with a table that is rendered by DataTable, and I have the requirement to dynamically append new elements inside the table like this: The dark grey area represents the new DOM elements that need to be inserted dynamically. The first row cont ...

What steps can I take to troubleshoot and fix the height of a div/span element?

Here is my HTML code: <div> <span style="display: inline-block;height:20px">20</span> <span style="display: inline-block;"><img src="img/ex.png"/></span> </div> The image I have in the second span is sized at ...

Create styles for each component based on their specific props when designing a customized Material-UI theme

I am having trouble styling the notchedOutline of a disabled <OutlinedInput /> in my custom MUI theme. My goal is to make the border color lighter than the default color when the input is disabled. Here is what I have attempted so far: const theme = ...

What steps can I take to ensure the reset button in JavaScript functions properly?

Look at this code snippet: let animalSound = document.getElementById("animalSound"); Reset button functionality: let resetButton = document.querySelector("#reset"); When the reset button is clicked, my console displays null: resetButton.addEvent ...

npm WARNING: The package @angular-devkit/[email protected] is in need of a peer dependency xxxx, however no installation for this dependency has

Attempting to launch an angular project and encountering the following errors: $ npm install npm WARN @angular-devkit/[email protected] requires a peer of @angular/compiler-cli@^14.0.0 but none is installed. You must install peer dependencies yoursel ...

PHP and JavaScript are two powerful programming languages that are

While I understand that PHP and JavaScript operate in different locations, I am curious to know if there is a way to incorporate some PHP code into my JavaScript file. I need to create unique URLs for linking to profiles and news posts, such as /#/news/IDH ...

Guide on how to navigate to a different page upon logging in with react-router-dom V5

I have implemented routing in my create-react-app using react-router-dom version 5.2.0. My goal is to use react-router for redirects and route protection within the application. The initial landing page is located at /, which includes the login/signup fun ...

Issue with displaying Buefy Material Design icons when using the b-icon component

This is my first time using Buefy I encountered an issue with the b-icon component, Rather than displaying the icon, I saw an empty block element which was confusing. Switching to a different icon pack did not resolve the problem either. ...

Sliding Image Menu using jQuery

I am struggling with creating a menu using jquery mouseenter / mouseout effects. My goal is to have a small icon displayed that expands to the left and reveals the menu link when a user hovers over it. The issue I am facing is that the effect only works w ...

"Challenges Arising in Deciphering a Basic JSON Array

After countless attempts, I am still struggling to solve this issue. My PHP code is functioning properly, as it returns the expected data when "Grove Bow" is selected from the dropdown menu: [{"wtype":"Grove Bow","was":"1.55","wcc":"5","wbdmin":"12","wbdm ...

Dealing with Axios cross-origin resource sharing problem in communication between VueJS frontend and SailsJS backend

I've tried everything to solve this issue but I'm still struggling to establish an Axios connection between my VueJs frontend and SailsJS backend. My Vue app is running on localhost:8080, while Sails is running on localhost:1337. Here is the erro ...

Unable to navigate to partial view within MEAN application

I'm currently following a tutorial on creating single page applications using the MEAN stack. So far, I have successfully rendered the index.jade view. However, I encountered an issue when trying to route to a partial view as the DOM of the page does ...

The validation for the start and end dates in the datepicker is not functioning properly when

I have integrated a bootstrap date picker into my website. However, I am encountering an issue where the end date validation does not update when I change the start date after the initial selection. <script type="text/javascript" src="htt ...

Communication through HTTP requests is not supported between docker containers

I currently have two applications running as services within a docker-compose environment. My React App A Node.js server In an attempt to make an HTTP request from my React app to the Node.js server, I am using: fetch("http://backend:4000/") However, w ...

Unlocking the power of namespaced Vuex getters in Mocha unit testing

I have been working on developing a new Vue component that utilizes a namespaced Vuex getter to retrieve a list of column names. The actual component is functioning properly and runs without any issues. During the Mocha unit testing phase, I set up a mock ...

What are the advantages of using history.push or another method from react-router-dom compared to simply assigning the path to window.location.pathname?

When I need to navigate within my code, I find it more convenient to simply assign the desired path to window.location.pathname. Can this approach have any drawbacks? ...

Leveraging the Power of JavaScript within Angular 12

Currently, I am in the process of learning how to utilize Angular 12 and am attempting to create a sidenav. While I am aware that I can use angular material for this task, I would prefer not to incorporate the associated CSS. My goal is to integrate this ...

How can the outcome of the useQuery be integrated with the defaultValues in the useForm function?

Hey there amazing developers! I need some help with a query. When using useQuery, the imported values can be undefined which makes it tricky to apply them as defaultValues. Does anyone have a good solution for this? Maybe something like this would work. ...

Can you show me a comprehensive list of all the REST endpoints for Express mounted Apps?

When working with Express 4, you can utilize the app._router.stack object to list your app routes. In one of the routes in my todos module routes file, I attempted to display this object by sending it as part of the response: exports.update = (req,res) = ...