Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Nuxt vuex-persistedstate no guarda el estado en el localstorage

Problema

Al actualizar el store de Vuex usando Nuxt con el plugin vuex-persistedstate no se actualiza el LocalStorage del navegador.

Solución

La clave radica en establecer que primero cargue nuxt y después actualice el Storage. Un simil sería el "onReadY" de jQuery para el navegador.

Paso a paso

plugins: [{ src: '~/plugins/vuex-persisted', ssr: false }]
  • Crear el plugin con el que vamos a trabajar: plugins/localStorage.js.

  • Código del plugin:

// ~/plugins/localStorage.js
import createPersistedState from "vuex-persistedstate";

export default ({store, isHMR}) => {
  // In case of HMR, mutation occurs before nuxReady, so previously saved state
  // gets replaced with original state received from server. So, we've to skip HMR.
  // Also nuxtReady event fires for HMR as well, which results multiple registration of
  // vuex-persistedstate plugin
  if (isHMR) return;

  if (process.client) {
    window.onNuxtReady((nuxt) => {
      createPersistedState()(store); // vuex plugins can be connected to store, even after creation
    });
  }
};

Webography

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.