'Can not catch Vuex state change in my Vue component

I have a Vuex store where I have a getter which works correctly and I can see the changes on the state. But if I call this getter as computed property in component it does not work. The value is still the same.

The store code looks like:

mutations: {
  UPDATE_SERVER_FILTERS(state, payload) {
    this._vm.$set(state, 'serverFilters', payload);
    //state.serverFilters = payload;  // Both patterns work
  },
  getters: {
    serverFilters(state) {
      return state.serverFilters;  // This works fine
    }
  }
}

The component code:

computed: {
  serverFilters() {
    return this.$store.getters[this.storeName + '/serverFilters'];
  },
}

Here is JSFiddle example https://jsfiddle.net/camo/je0gw9t3/4/ which works fine. And it is a problem cause in my project it does not work. I am prepared to die...

How can I solve it?



Solution 1:[1]

In the most bottom part:

new Vue({
  store,
  el: '#example',
  data() {
    return {};
  },
  computed: {},
  methods: {
    changeFilters() {
      this.$store.dispatch(this.storeName + '/updateFilters');
      //                   ^^^^^^^^^^^^^^ there is no storeName 
    },
  },
});

The changeFilters method. You are using this.storeName, but there is no this.storeName! Just like the Child component, add storeName: 'a' to the data() then it should work.

https://jsfiddle.net/4yfv3w87/


Here is the debug process for your reference:

First open the Vue Devtools and switch to the timeline tab. And just click the button, you will see that there is no action is being fired. So the problem must be the one who dispatches the action. And then you will notice that the root component doesn't have a storeName.

So don't panic, just try to trace the code. It will only take a few minutes to find out the issue!

Solution 2:[2]

Computed properties might have problem to make an observer reference from returned value out of function. Instead of chaining getters and computed properties, why you don't use just getters or computed properties ? In my opinion, it's a bad practice to use them both, and I can't imagine a situation you need it. So if you need filter operations in many components, just make a getter and use getter in components instead of computed properties.

If you really want to chain them, try this:

new Vue({
    store,
    el: '#example',
    data() {
        return {
        storeName: 'a'
      }
    },
    computed: {
      filters() {
          get() {
              return this.$store.getters[`${this.storeName}/getFilters`];
          }
          set(newValue) {
              this.$store.dispatch(this.storeName + '/updateFilters');
          }
      },
    },
})

Comment please if someone check it. I don't know are it works.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2