What does cart.getItem('cart') do?
Aug 14, 2019
5
Level 2
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?
Please or to participate in this conversation.