tuscior
tuscior

Reputation: 99

Rerender component after state change vue.js

I am working with NuxtJS and VueJS. I'm having a problem with a component not re-rendering after the state changed.

index.js file

Vue.use(Vuex)

const state = {
  productsHome: [],
  accessToken: {},
  collections: {},
  product: {},
  cart: {},
}

const getters = {
  productForHomepage (state) {
    return state.productsHome
  },
  productForPdp (state) {
    return state.product
  },
  cart (state){
    return state.cart
  }
}

const actions = {
    nuxtServerInit (context) {
      //good place to set language
    },
    GET_HOME(){
      api.getHomepageProducts().then(response => {
        this.commit('setHomeProducts', response.data)
      })
    },
    GET_PDP(sth){
      api.findBySlug(this.app.router.history.current.params.slug).then(response => {
        this.commit('setPDPData', response.data)
      })
    },
    ADD_TO_CART(store, id){
      api.addToCart(id).then(res => {
        store.commit('updateCart', res.data)
      })
    }
  }

const mutations = {
  setHomeProducts(state, data){
    state.productsHome = data
  },
  setPDPData(state, data){
    state.product = data[0]
  },
  updateCart(state, data){
    for (var optbox of data) {
      state.cart[optbox.id] = optbox;
    }
    // state.cart.set('iteams', 'count', 1)
  }
}

const createStore = () => {
  return new Vuex.Store({
    state,
    getters,
    mutations,
    actions
  });
}

export default createStore;

and this is the component

<template>
  <div>
    <div class="content">
      <p>
        This is cart
      </p>
      {{ cart }}
    </div>
  </div>
</template>
<script>

export default {
  data() {
    return {
      cart: this.$store.state.cart
    }
  },
  watch: {
    cart: function(val){
      cart = this.$store.state.cart
    }
  },
  methods: {
    updateCart: function(){
      console.log(this)
    }
  }
}
</script>

Upvotes: 3

Views: 5321

Answers (1)

craig_h
craig_h

Reputation: 32704

When you do this:

  data() {
    return {
      cart: this.$store.state.cart
    }
  }

You initilise the data with the value of the cart state, but it won't keep changing when the cart state changes, it's a one time deal, as you can see in this JSFiddle

What you actually want to do is use a computed:

computed: {
  cart(){
    return this.$store.state.cart
  }
} 

Now whenever cart state changes in your store, so too will the value of cart in your component.

And here's the JSFiddle for that: https://jsfiddle.net/craig_h_411/zrbk5x6q/

Upvotes: 2

Related Questions