Summer Sale! All accounts are 50% off this week.

liquidsword's avatar

Load localstorage to state on load (Vuex)

I am implementing a cart on my website. When a user adds or removes an item the state updates, then the local storage. Currently, if a user were to leave the page or reload the page the state and local storage are out of sync. One solution I found was to load the local storage on the main Vue instance.

app.js

const app = new Vue({
    el: '#app',
    components: { App },
    router,
    store,
    beforeCreate() {
        this.$store.commit('LOAD_CART');
    }
});

../store/index.js

const mutations = {
   [types.LOAD_CART] (state) {
      cart.getItem('cart').then(function (value) {
         if(value !== null) {
            state.added = value;
         }
   });
}

When I do this Vue squawks

[vuex] do not mutate vuex store state outside mutation handlers.

What's the correct way to handle this?

0 likes
5 replies
bugsysha's avatar

Maybe it's due to promises that you have in your mutations. Move that to actions and from that action call/commit mutation.

Please or to participate in this conversation.