Todilo
Todilo

Reputation: 1333

Vuex computed property that listens to getter not updating

I have a problem where my computed properties (that basically just calls a store getter with an id) does not get re-computed when the store changes. Anyone know why?

Product computed (isInCart is the relavant one, the other just show that state changes works)

isInCart() {
    var isInCart = this.$store.getters['shoppingCart/isInCart'](this.product.id);
    return isInCart;
  }

Vuex store

const getters = {
  count: state => state.items.length,
  hasItems: state => !!state.items.length,
  isInCart(state) {
    return id => state.items.findIndex((item) => {
      return item.productId === id; 
    }) > -1;
  }
}

and state change is done by a mutation like this:

setCart(state, cart) {
    state.items = cart.items;
  },

The initial call to the getter works as expected. It's just that when the state is changed it is not ran again. The other getters "hasItem" and "count" work as expected.


I also tried in my component to put the function directly into the computed like so:

computed: {
     ...mapState({
        isInCart(state) {
          var id = this.product.id;
          return !!state.shoppingCart.items.filter(item => item.productId === id).length
        }
      })
    },

Upvotes: 5

Views: 7747

Answers (1)

J.L.
J.L.

Reputation: 74

This is because the getter returns a function. Each state that a getter dependent on is an observer. It observes the change of these dependencies. Any change can trigger the getter to run. But, if the getter just returns a function, you won't get the result of this function. Instead, you get a result of a function with updated value.

Upvotes: 3

Related Questions