How to save the state of the basket in Vuex after a reboot (store is divided into modules (menu, products, basket))?

    1 answer 1

    There is a wonderful plugin called vuex-persistedstate

    yarn add vuex-persistedstate@latest 

    This plugin uses localStorage (or sessionStorage , if passed by a parameter) of the browser to save the current state of the application:

     import Vue from 'vue'; import Vuex, { Store } from 'vuex'; import createPersistedState from 'vuex-persistedstate'; Vue.use(Vuex); export default new Store({ // ваш стСйт state: {}, // ваши ΠΌΡƒΡ‚Π°Ρ†ΠΈΠΈ mutations: {}, // ваши ΡΠΊΡˆΠ΅Π½Ρ‹ actions: {}, plugins: [createPersistedState()] }); 

    Do not forget to register the store in the application initialization:

     import store from './path-to-store'; new Vue({ store, render: (h) => h(YOUR_APP_COMPONENT) }).$mount('#app'); 

    In short, what this plugin does:

     localStorage.setItem(key, JSON.stringify(state)); 

    Saving to localStorage occurs after each commit , and reading after each page load:

     // source ΠΊΠΎΠ΄ Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ `getState` ΠΈΠ· ΠΏΠ»Π°Π³ΠΈΠ½Π° function getState(key, storage, value) { try { return (value = storage.getItem(key)) && typeof value !== 'undefined' ? JSON.parse(value) : undefined; } catch (err) {} return undefined; } 

    Since your storage is divided into modules, each module must have a local namespace:

     const cart = { namespaced: true, state: { ... } }; new Store({ ....., modules: { cart } }); 

    This allows us to avoid the conflict of mutations with the same name, commit a mutation through the name of the module + / + mutation:

     store.commit('cart/mutationName', mutationValue); 
    • Described the code that I have with the plugin - why it does not work - Aex Fun
    • @AexFun, well, firstly bring the plugin to the top level, to the main store - overthesanity
    • Yes, I have a namespaced: true, but even when I brought it to the main store, why it does not work, moreover, even the main one does not open (I launch via webpack with the command npm run dev) - Aex Fun
    • yeah, brought the plug-in to the main store and put it at the very end - URA earned) thank you very much - Aex Fun
    • Every time I run npm run dev, the state is saved, and when the spa is uploaded to the hosting, will the status be reset to zero or will it also be saved each time the server is accessed? - Aex Fun