Search code examples
vue.jsvuexsession-storagevuejs3

Object from sessionStorage not reactive in vuejs / vuex


I know this is a noob question but I can't figure it out despite looking through different posts. Please help. I'm building a shopping cart with Vue and Vuex. I store the content of the cart in sessionStorage so that it persists if the user refreshes.

When the page loads, I am able to retrieve the cart from session and add it to vuex state but it doesn't reflect in the DOM until I add a new item to the cart. How can I solve this?

This is my code: I check to see if there's any session in beforeUpdate:

beforeUpdate() {
  // this fires twice. why?
  let cart = this.store_slug + '_cart'
  found_cart = JSON.parse(sessionStorage.getItem(cart))
  if (found_cart) {
    this.$store.commit('restoreCart', found_cart)
  }
},

This is my 'restoreCart' mutation:

restoreCart(state, found_cart) {
  state.cart.push(found_cart)
},

Solution

  • The mistake in your current code is that you are trying to push the old cart into the current one as if it (the old cart) was a product item. You should actually assign the old cart to the new one

    restoreCart(state, found_cart) {
      state.cart = found_cart;
    },
    

    It depends on how you use your store to read the current cart contents but something like this will instantly update when you restore the old cart:

    <div v-for="item in $store.state.cart" :key="item.id">
    {{ item.name }}
    </div>