How To Watch Mutation In Vuex Plugin

499 Views Asked by At

I am having an issue with a plugin I am attempting to use. Note that code works fine after refreshing page however on initial login the mutation it is set to watch (createSession) is not responding correctly. I am not sure if anyone is familiar with the CASL package, but I don't think the issue is there but perhaps something I need to be doing to make the plugin work correctly.

Here is the plugin ability.js

import { Ability } from '@casl/ability'

export const ability = new Ability()

export const abilityPlugin = (store) => {
    ability.update(store.state.rules)

    const rules = store.subscribe((mutation) => {
        switch (mutation.type) {
            case 'createSession':
            ability.update(mutation.payload.rules)
            break
            case 'destroySession':
            ability.update([{ actions: '', subject: '' }])
            break
          }
          console.log(ability.rules)
      })
      return rules
  }

Here is the store where I am importing

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import { abilityPlugin, ability as appAbility } from './utils/ability'
import storage from './utils/storage'

export const ability = appAbility
Vue.use(Vuex)
axios.defaults.baseURL = 'http://traxit.test/api'



export default new Vuex.Store({
  plugins: [
    storage({
      storedKeys: ['rules', 'token'],
      destroyOn: ['destroySession']
    }),
    abilityPlugin
  ],
  state: {
    rules: '',
token: localStorage.getItem('access_token') || null,
    sidebarOpen: true,
    loading: false,
  },
 mutations: {
    createSession(state, session) {
      state.rules = session[0]
      state.token = session.access_token
    },
}

and I am mutation the createSession with my response data from the initial login action which is to retrieve token and rules here

retrieveToken({ commit }, credentials) {

      return new Promise((resolve, reject) => {
          axios.post('/login', {
              username: credentials.username,
              password: credentials.password,
          })
          .then(response => {
              const token = response.data.access_token

              localStorage.setItem('access_token', token)
              commit('createSession', response.data)
              resolve(response)
          })
          .catch(error => {
              console.log(error)
              reject(error)
          })
      })
    },

any help would be greatly appreciated!! I have been stuck on this issue for a while..

1

There are 1 best solutions below

0
TJ Weems On BEST ANSWER

Once again answering my own question. Lol

So after console loggin my mutation.payload I realized I was trying to access the data incorrecly.

I switched

case 'createSession':
        ability.update(mutation.payload.rules)
        break

to this

case 'createSession':
        ability.update(mutation.payload[0])
        break