Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuex getter not updating on state changes

I can't get a vuex getter to update, when a state object changes. I'm trying to get a vuex getter to return a total sum of the values in a state object, with a reduce function.

// Mutation
state.shippingFees[method.sellerId] = method.fee; // state.shippingFees = { 1: 1900 }; etc.

// Getter
totalShippingFees: state => Object.values(state.shippingFees).reduce((total, fee) => total + fee, 0)

After setting a shipping fee key-value pair in the state.shippingFees object, the getter still just returns 0.

like image 874
Kris D. J. Avatar asked Dec 13 '22 12:12

Kris D. J.


1 Answers

Vue does not allow dynamically adding new root-level reactive properties to an already created instance. However, it’s possible to add reactive properties to a nested object using the Vue.set(object, key, value) method

Hence the way you are updating above object it is not reactive. Hence your values are not updated in the getter. To know more about vue reactivity read here.

For making it reactive you need to use $set or object.assign

Update your mutation as below =>

Vue.$set(state.shippingFees,method.sellerId,method.fee);
like image 118
Riddhi Avatar answered Dec 18 '22 18:12

Riddhi