Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How save user connection in Local storage Nuxt.js?

I am making an application in nuxt.js, I use a store to store data including the user who connects and I want to keep the user’s connection elements in the localStorage. So to do this I used a plugin which is vuex-persist of which here is the code.

Here is my store/login.js :

export const state = () => ({
    user: ''
})

export const mutations = {
    setUser(state, newUser) {
        state.user = newUser;
    }
}

export const getters = {
    getUser(state) {
        return state.user
    }
}

Here is my plugin/vuex-persist.js :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import VuexPersistence from 'vuex-persist';

export default ({ store }) => {
  window.onNuxtReady(() => {
    new VuexPersistence({
      key: "vuex",
      storage: window.localStorage,
      reducer: state => ({ login: state.login }),
    }).plugin(store);
  });
};

So this saves the user in localStorage, for example:

enter image description here

But when I refresh the page or when I open a new page in a new tab I have to reconnect all the time.

I don’t understand why because when I don’t put a reducer function in my plugin I don’t need to constantly reconnect but the problem is that it doesn’t just save the user in localStorage.

Thanks for your help

>Solution :

I do not know the issue with your plugin, maybe it isn’t registered correctly within nuxt.config.js?

// Inside - nuxt.config.js
export default {
   plugins: [{ src: '~/plugins/vuex-persist.js', mode: 'client' }],
}

or the issue could be the use of the plugin in combination with:

  window.onNuxtReady(() => {

since i personally never needed the onNuxtReady with the loading of any external plugins/libraries and within the documentation of said plugin it isn’t mentioned.

Nevertheless, you could look into using the library vuex-persistedstate which basically does the exact same thing and i never had any issues with it.

Apologies for not really answering your question but i thought maybe suggesting the other library could help you or anyone else

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading