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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.