2

I'm currently using this plugin vuex-persistedstate

and I would like to use it with Vuex module of my Nuxt app.

Basically I have a login module if success, then store the authToken coming from the response to localStorage

Here's my code:

import axios from "axios";
import createPersistedState from 'vuex-persistedstate';

export const state = () => ({
  signInAttrs: {
    email: "",
    password: ""
  },
  authToken: ""
});

export const mutations = {
  SET_AUTH_TOKEN(state, token) {
    state.authToken = token;


    createPersistedState({
      key: 'admin-auth-key',
      paths: [],
      reducer: state => ({
        authToken: '123123123'
      })
    })(store);
  }
};

export const actions = {
  signInAdmin({ commit }, context) {
    return axios.post(`${process.env.BASE_URL}/sign_in`, {
      email: context.email,
      password: context.password
    }).then(response => {
      commit('SET_AUTH_TOKEN', response.data.headers.token);
    }).catch(error => {
      console.log(`failed ${error}`);
    });
  }
};

export const getters = {
  signInAttrs(state) {
    return state.signInAttrs;
  },
  authToken(state) {
    return state.authToken;
  }
};

Inside the mutations there's SET_AUTH_TOKEN that receives the token as the parameter from API. How can I save it to localStorage?

AllenC
  • 2,754
  • 1
  • 41
  • 74

1 Answers1

3

I think you're misunderstanding usage of vuex-persistedstate. Once you add it to Store plugins (plugins: [createPersistedState()]), it automatically updates localStorage variable vuex with a copy of your store on each mutation commit (see example). So your token should be inside vuex.authToken in localStorage already.

If you want to simply store a variable with custom name you can do it without plugins: localStorage.setItem('key', 'value'). See this question.

Kyryl Havrylenko
  • 674
  • 4
  • 11
  • Do not forget to include Vuex-persistedstate as a Nuxt plugin (documented on GitHub). You can also use the option `path` for `createPersistedState` to filter what parts of your Vuex state to be persisted. – IVO GELOV Jan 28 '19 at 10:44