Home > Enterprise >  How to re-direct to login page from vuex action in vue
How to re-direct to login page from vuex action in vue

Time:02-28

Hi i have a existing project where in all action.js we are dispatching logoutFromServer upon 401 Unauthorized

here is how it will look like this

users.action.js

 async getAllUsers(context,payload={}){
    try{
       let resp = await axios.get(...);
    }catch(error){
       if(error.response.status == 401)
         context.dispatch('logoutFromServer');
    }
 }

customers.action.js

async getAllCustomers(context,payload={}){
    try{
       let resp = await axios.get(...);
    }catch(error){
       if(error.response.status == 401)
         context.dispatch('logoutFromServer');
    }
 }

there above code is repeated in almost every GET,POST,PUT,DELETE at least more than 1000 places(so i cannot change them now). upon dispatch of logoutFromServer i'm getting

TypeError: Cannot read properties of undefined (reading 'push')

for below code

authentication.action.js

 async logoutFromServer(context){
    try{
     let resp = await axios.delete(...);
    }catch(e){
       console.log('must be already deleted');
    }
    //clear cookie 
    this.$router.push({name:"login"})   <-- here the above error occurs i,e  `TypeError: Cannot read properties of undefined (reading 'push')`
 }

Question: how to re-direct from vuex actions to /login route

Please help me thanks in advance !!

CodePudding user response:

you can explicitly import the router and use it.

==> router.js

import Vue from "vue";
import VueRouter from "vue-router";


Vue.use(VueRouter);

export const router = new VueRouter({
    mode: 'hash',
    base: "./",
    routes: [
      { path: "/", component: home},
      ...
    ]
})

===> actions.js

import {router} from "../router.js"

export const someAction = ({commit}) => {
    router.push("/");
} 
  • Related