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.
Your code is fine and Vuex is successfully "committing" your data to the store. The issue you're experiencing is coming from the fact that Vuex (out of the box) does not persist your data in localStorage, which I believe is what you mean by "commit". As has been mentioned a couple times in comments on your question, you are going to need to use a third party package (most people use Vuex-PersistedState, but I prefer Vuex-Persist as it's more customizable and supports Typescript). Either one is very easy to get started with.
With Vuex-PersistedState, you'll need to update your Vuex initialization with the new plugin. It should look something like this:
import createPersistedState from 'vuex-persistedstate' // import the package
const store = new Vuex.Store({
plugins: [createPersistedState()] /// include the imported plugin
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With