One of the modules in my Vuex store is called login.js and it looks like this:
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
};
The code for login.vue:
methods: {
...mapActions(["getToken"]),
login() {
const userdata = {
email: this.email,
password: this.password,
remember_me: true
};
this.getToken(userdata);
}
}
The issue I'm facing is that the token gets set correctly the first time when logging in, but upon refreshing the browser, the access_token
is lost.
When checked in the browser, it looks like this:
https://i.sstatic.net/Hh8HB.png
However, committing via dev tools works and keeps the state persistent.
I've looked at similar questions on SO but couldn't find a solution:
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 ensure that the state.access_token
remains persistent without losing its value upon page refresh?