0

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)
},
5
  • 1
    Why do you push the card into an array ? Is your application going to have more than 1 card simultaneously ? Commented Jun 16, 2020 at 14:18
  • Thanks @IVOGELOV this has solved one of the problems I was having (adding to cart was creating a new cart item instead of updating the existing one). I didn't realise I was pushing the "session" cart into the "state" cart. It is still not reactive though. Commented Jun 16, 2020 at 14:33
  • You mean that state.cart = newObject does not have any effect ? Commented Jun 16, 2020 at 14:42
  • state.cart = newObject i.e. state.cart = found_cart has an effect. I can see in the vuejs browser extension that the item is in the cart but when I navigate to my cart, the items are not displayed. However, if I add a new item to the cart, both the new and old items are then displayed. Commented Jun 16, 2020 at 15:09
  • Hey @IVOGELOV I added a subsequent function that used the items in cart after restoring it and it displays now. This has the same effect of $nextTick although I was unable to use $nextTick. Your solution worked if you'd like to post it. Thank you! Commented Jun 16, 2020 at 16:26

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

You missed out the ">" for the opening div tag

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.