Home > Mobile >  How save user connection in Local storage Nuxt.js?
How save user connection in Local storage Nuxt.js?

Time:02-23

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 :

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

CodePudding user response:

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

  • Related