Skip to content

Instantly share code, notes, and snippets.

@mrroot5
Created August 12, 2019 09:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrroot5/b4aafe1dc142ac7436c89d93154a7132 to your computer and use it in GitHub Desktop.
Save mrroot5/b4aafe1dc142ac7436c89d93154a7132 to your computer and use it in GitHub Desktop.
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