I have a vuex store module called login.js as below
import axios from "axios";
import router from "@/router";
axios.defaults.baseURL = process.env.VUE_APP_API_ENDPOINT;
const state = {
access_token: localStorage.getItem("access_token") || null,
};
const getters = {
loggedIn() {
return (
state.access_token != null && localStorage.getItem("access_token") != null
);
}
};
const mutations = {
doLogin(state, response) {
const token = response.authentication_data.access_token;
localStorage.setItem("access_token", token);
state.access_token = token;
router.push("/admin");
};
const actions = {
async getToken({ commit }, userdata) {
let email = userdata.email;
let password = userdata.password;
let remember_me = userdata.remember_me;
await axios
.post("auth/login", null, {
params: {
email,
password,
remember_me
}
})
.then(response => {
if (response.data.meta.status == "true") {
commit("doLogin", response.data);
} else {
alert("wrong password");
}
})
.catch(error => {
alert(error);
});
};
export default {
state,
getters,
actions,
mutations
};
login.vue code
methods: {
...mapActions(["getToken"]),
login() {
const userdata = {
email: this.email,
password: this.password,
remember_me: true
};
this.getToken(userdata);
}
}
The login function works and the token is set for the 1st time but when I refresh the browser the access_token
is gone.
In the browser, it's shown as below
But if I commit via dev tools it works and the state becomes persistent.
The similar nature questions on SO but don't answer this question.
vuex commit does not commit to store
Vue2 + Vuex Commit Not Committing (without Vue devtools)
Vuex Mutation running, but component not updating until manual commit in vue dev tools
How can I make the state.access_token
persistent via the code? The problem is with a page refresh I lost state.access_token
value.
state.access_token
– Techie