The isLoggedIn in getters is always true event if there is no token from API i can stil go to every routes i don't know what is the error in guard route or i'm storing token wrong in state. in this statement is not working if(!store.getters.isLoggedIn){ go to login} plz help me i'm stuck :(
in store.js
state:{
Token: localStorage.getItem('access_token') || null,
}
mutations:{
AUTHENTICATION(state,token){
state.Token = token;
},
UNAUTHENTICATION(state,response){
state.Token = response;
}
},
getters:{
isLoggedIn(state){
return state.Token !=null;
}
},
actions:{
loginUser({commit}, formData){
http.post("/login",formData).then((response)=>{
if(response.data.status === 'success'){
const token = response.data.token;
localStorage.setItem('access_token',token);
localStorage.setItem('user',response.data.user);
commit('AUTHENTICATION',token);
router.push({name:'Dashboard'});
router.go();
}else{
commit("LOGIN_ERROR",response.data.message);
}
})
.catch((error)=>{
if(error){
commit('UNAUTHENTICATION',null);
localStorage.removeItem('access_token');
commit("GET_ERRORS",error.response.data.errors);
}
});
});
},
logoutUser({commit}){
http.post("/auth/logout").then((response)=>{
if(response.data.status === "success"){
localStorage.clear();
commit('UNAUTHENTICATION',null);
router.push({name:'Login'});
window.location.reload();
}else{
commit("LOGIN_ERROR",response.data.message);
}
})
.catch((error)=>{
if(error){
commit("GET_ERRORS",error.response.data.errors);
}
});
}
},
in route.js
route.beforeEach((to, from, next) => {
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
if(requiresAuth){
if(!store.getters.isLoggedIn){
next({name: 'Login'});
}else{
next();
}
}else{
next();
}
});
CodePudding user response:
Try with :
if(!store.getters.isLoggedIn || store.getters.isLoggedIn === '') {
//...
and getter :
isLoggedIn: (state) => state.Token,
CodePudding user response:
while there is no access_token
in your local storage then localStorage.getItem('access_token')
will return the value undefined
which is not equal to null in non-strict not version !=
so you getter will be always true
instead, you should use (strict not version) or (double not version ):
option 1 :
getters:{
isLoggedIn(state){
return state.Token !== null; //double equals
}
}
option 2 :
getters:{
isLoggedIn(state){
return !!state.Token; // double !
}
}