Utilize Vuex mutators within route navigation guards

Hey there, I'm currently working on an app using Laravel and VueJS. To restrict certain routes, I've implemented navigation guards. However, I'm facing an issue where I need to access Vuex mutators to determine if the current user is logged in. Even though the store is properly defined, I encounter an error message saying

TypeError: Cannot read property 'commit' of undefined
when trying to use the mutator from the router. Any suggestions on how to resolve this? Thank you!

routes

import Vue from 'vue'
import Router from 'vue-router'

import Hello from '@/components/Hello'
import Register from '@/components/Register'
import Login from '@/components/Login'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Hello',
      component: Hello,
      meta: {
        showNavigation: true,
        requireAuthentication: true
      }
    },
    {
      path: '/register',
      component: Register,
      meta: {
        showNavigation: false,
        requireAuthentication: false
      }
    },
    {
      path: '/login',
      component: Login,
      meta: {
        showNavigation: false,
        requireAuthentication: false
      }
    }
  ],
  mode: 'history'
})

store

import Vue from 'vue'

import Vuex from 'vuex'

Vue.use(Vuex)

export const store = new Vuex.Store({
  state: {
    access_token: null,
    expires_in: 0
  },
  mutations: {
    setToken (state, response) {
      state.access_token = response.body.access_token
      state.expires_in = response.body.expires_in + Date.now()
    },
    getToken (state) {
      if (!state.access_token || !state.expires_in) return null

      if (state.expires_in < Date.now()) this.commit('destroyToken')

      return state.access_token
    },
    destroyToken (state) {
      state.access_token = null
      state.expires_in = 0
    },
    isAuthenticated (state) {
      return this.commit('getToken') !== null
    }
  },

  actions: {
    getOauthToken (context, user) {
      var data = {
        client_id: 2,
        client_secret: 'XXXXXXXXXXXXXXXXXXXXXXXXXX',
        grant_type: 'password',
        username: user.email,
        password: user.password
      }

      Vue.http.post('oauth/token', data)
      .then(response => {
        context.commit('setToken', response)
      })
    }
  }
})

main.js

import Vue from 'vue'
import App from './App'
import router from './router'
import { store } from './store'

import VueResource from 'vue-resource'
import VeeValidate from 'vee-validate'

Vue.config.productionTip = false

Vue.use(VueResource)
Vue.use(VeeValidate)

Vue.http.options.root = 'http://codex.app'

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requireAuthentication)) {
    console.log(store)
    console.log(store.commit('isAuthenticated'))
    if (!store.commit('isAuthenticated')) {
      next('/login')
    } else {
      next()
    }
  } else {
    next()
  }
})

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: { App }
})

Answer №1

When making mutations, it involves altering the state and specifically the state only. If you require more intricate changes to the state, opt for using actions instead.

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

Implementing Asynchronous Rendering in React Router 4

I've been working with React Router 4 and trying to implement Redirect(Auth) following a guide. However, I'm facing an issue with rendering based on the promise returned by an AJAX call. It seems like my rendering logic inside the promise is not ...

Is it necessary for the error event of xmlhttprequest to include an error message?

Currently, I am in the process of developing an AJAX request within a Firefox extension. The following code snippet illustrates my approach: function GetMenu(){ var oReq = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(); ...

Place the text within the contenteditable body of a frame at the specific caret position

Within my iframe object, there is a contenteditable body. I am trying to paste text or HTML elements at the caret position. However, when I attempted this code snippet, I encountered an error message saying Cannot read property 'createRange' of u ...

Error: Google chart for Google Maps is not displaying text every 1 unit as expected

I am looking to display all the hAxis labels in my chart. Due to the extensive length of the code exceeding 4000 lines, I will only include what I consider to be crucial: var data = new google.visualization.DataTable(); data.addColumn('string', & ...

Copying content from one website to another using JavaScript

Currently, I am working on a website which stores data and I require assistance in transferring this data to another site. If you have any suggestions using Javascript or other methods, please let me know. ...

easy method for creating a hyperlink that triggers a "download" pop-up box

Is there a simple and efficient way to have some of my links trigger the 'save file as' prompt (similar to right-clicking) immediately after they are clicked for the first time? ...

Managing backslashes during the processing of JSON

I am currently facing an issue with a JSON string that I am trying to parse using the JSON.parse method. The problem seems to be related to the presence of backslashes and parentheses in the string, which results in an 'invalid character' error. ...

Adding data to an AngularJS template

I am encountering an issue with a flag that I am toggling between true and false to alter the display of certain elements on my page. While it works outside of the template, integrating this value into the template itself has proven challenging. restrict: ...

Include the session variable as an argument in the onload() function call

I've encountered a problem while trying to send the session variable $_SESSION["post-code"] as a parameter in the following code snippet... <body onload="getLocation('<?php echo $_SESSION['post-code'];?>')"> Within my ...

I am currently attempting to create a JavaScript function that searches for the <td> elements within an HTML table. However, the function fails to work properly when there are <th></th> tags included

UPDATE: Scratch that, I managed to solve my issue by creating a separate table for the header to contain all of my <th> tags I am working with an HTML table and I would like to add a search bar to filter through the content since it is quite large. ...

Goodbye.js reliance on lodash

In my search for the most lightweight and speedy jQuery implementation for server-side NodeJs, I've come across Cheerio as the best option. However, I've noticed that Cheerio has a code-size of around 2.6 MB, with approximately 1.4 MB attributed ...

Are third-party scripts and HTML widgets able to replicate your website's data, including cookies, HTML, and other elements?

Currently, I am in the process of constructing a website that incorporates a third-party weather HTML widget. The widget is sourced from a trusted and reliable source on the web. It consists of a link and small JavaScript tags that are executed once loaded ...

Enhancing Your Website with Interactive Highlighting Tags

Looking at the following html: Let's see if we can <highlight data-id="10" data-comment="1"> focus on this part only </highlight> and ignore the rest My goal is to emphasize only the highlight section. I know how to emphasize a span ...

Incorporating Ajax to allow users to choose an option from a selection for

I want to populate a dropdown menu with values received from an ajax call in the form of a json array. However, the current code results in an empty select element being created. $.ajax({ type: "GET", url: "/wp-content/gta/search_airport.php", data: ...

Stop jQuery popups from wrapping text when resizing the browser window

Whenever a link is clicked, a jQuery popup appears. The popup functions properly in terms of opening and closing, but I would like to ensure that its position remains fixed when resizing the browser window to avoid any wrapping issues. Typically, I use a ...

What is causing the 'Invalid Hook Call' error to appear in React?

I have recently started learning React and I am currently working on converting a functional component into a class component. However, I encountered an error message that says: Error: Invalid hook call. Hooks can only be called inside of the body of a fu ...

Navigating global variables and functions in Vue3 with TypeScript

Feeling lost in the world of Vue.js, seeking guidance here. Attempting to handle global data and its corresponding functions has led me on a journey. Initially, I experimented with declaring a global variable. But as more functions came into play, I trans ...

In the Swiper function of JavaScript within a Django template, the occurrence of duplicate elements (products) is being generated

Experimenting with displaying products in a Django template, I decided to utilize the Swiper js class. This allowed me to showcase the products within a div, complete with navigation buttons for scrolling horizontally. However, when testing this setup wit ...

Link AngularJS service array length property to the controller's scope through binding

I am attempting to connect the length of an array from another service to my controller's scope in the following manner: app.controller('TestCtrl', function ($scope, safePostService) { $scope.count = safePostService.queue.length; $ ...

Mastering TypeScript in Router Configuration

I am currently working with a standard router setup. type Routes = '/' | '/achievements' | ... ; This helps in identifying the routers present in the project. However, I am faced with a new challenge of creating an array that includes ...