3

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>
2
  • 1
    You haven't stated what the problem is. Commented Nov 7, 2017 at 22:27
  • Cleaned up question. Commented Nov 8, 2017 at 1:25

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

Comments

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.