How to get localstorage data inside vuex state with Nuxt.js

Viewed 5605

I'm building a shopping cart with Nuxt. but when i refresh the page the basket automatically empties.

I try librairies like vuex-persist , vuex-persistedstate ... but I did not have a solution.

Now Im looking a way to get the initial state of cart directly from local storage like this.

state: {
      cart: [] //here what i want => window.localStorage.getItem("cart")
    }

Thanks a lots.

2 Answers

You can access localStorage only in browser. Its not accessible during SSR. So you need to create create a mutation in vuex store that will do what u want and commit it in mounted hook ( mounted executed only in browser ).

E.g.

...
mounted() {
 this.$store.commit('myMutation', window.localStorage.getItem("cart")
}

use nuxt-vuex-localstorage it works great and syncs with vuex

Related