1
votes

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

enter image description here

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.

1
Try using this github.com/robinvdvleuten/vuex-persistedstate, I use it in my store>index.js like this: import createPersistedState from 'vuex-persistedstate' import Cookies from 'js-cookie' Vue.use(Vuex) // Create a new store const store = new Vuex.Store({ plugins: [ createPersistedState({ getState: (key) => Cookies.getJSON(key), setState: (key, state) => Cookies.set(key, state, { expires: 3, secure: false }) }) ], actions, getters, mutations, state }) but you can use localStorage instead of cookiesSdpotts93
@Sdpotts93 This is not about local storage rather state.access_tokenTechie
@Techie Which you need to store in local storage if you want it to persist after a page refresh.ceejayoz
Please refer to the code sample. I have stored the access_token and retrieving as wellTechie

1 Answers

1
votes

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
})