Modermo
Modermo

Reputation: 1992

Push route from within action in Vuex Store

Trying to push route change from within the store. I tried importing router into the store itself and then doing something along the lines of:

LOG_OUT({commit}){
  commit('LOG_OUT__MUTATION');

  router.push({
   name: 'Login' 
  })
}

... but that didn't work.

I also don't want to push a route change from directly with the components because it would mean I need to check authentication and push a route change in every component, which seems cumbersome to me.

Edited:

The LOG_OUT__MUTATION clears the token stored in the state.

Upvotes: 3

Views: 6309

Answers (2)

Modermo
Modermo

Reputation: 1992

I finally figured this out.

Final Implementation

In your store, simply import the router:

import router from '@/router/index'

actions: {

  LOG_OUT({commit}){
    commit('LOG_OUT__MUTATION');

    router.push({
      name:'Login'
    })
  }

}

And then from another part of my app, I simply imported store and dispatched an action:

import Store from '@/store/store'

myFunction () {
  Store.dispatch('LOG_OUT');
}

Initial Implementation

Here was my implementation of Daksh Miglani's solution (which works). In my store.js, I had:

export const forceLogout = (commit) => {

  return new Promise((resolve, reject) => {
    commit('LOG_OUT__MUTATION');
    resolve();
  })

}

export default new Vuex.Store({
  actions,
  mutation
})

And then in another part of the app (helpers.js), I had:

import Store from '@/store/store'
import { forceLogout } from '@/store/store'
import router from '@/router/index'

forceLogout(Store.commit)
  .then(() => {
    debugger;
    router.push({
      name:'Login'
    })

  }).catch((error) => {
     console.log(error)
  })

Upvotes: 6

Daksh M.
Daksh M.

Reputation: 4815

Okay, I have a solution for you buddy:

So firstly you write a store committing function like this:

export const commitLogout = ({commit}) => {
  return new Promise((resolve, reject) => {
    commit('LOG_OUT__MUTATION');
    // once you're done with your clearing, resolve or reject the promise
    resolve();
  });
}

This function will return a promise, that you can use in your logging out function which will at the end allow you to commit and clear first and then logout.

Then you use this function as your logout function:

...

  logout() {
    commitLogout().then(() => {
      this.$router.push({
       name: 'Login' 
      })
    })
  }

...

Upvotes: 1

Related Questions