Search code examples
vue.jsdynamicstatevuexstore

Computed properties are not reacting to state change


I am working on a product overview page, that send out an API-call based on the current Category you are looking at:

    store.dispatch("tweakwise/fetchAPIAttributesLayeredNavigation", {
     tweakwiseCategory,
     this.pageNumber,
}

In my Store, the data from this API-call will be set in the following VueX Store State:

this.$store.state.tweakwise.tweakwiseLayeredNavigationAttributes: []

I want to react to this data in my front-end but my Computed methods do not seem to react to this change. As you can also see in the function below I added a Catch to prevent a "Non defined" error. The function, however, will not be called after the state has been set. This computed property is also added to the Mount() op the component

computed: {
    initialFetchProducts() {
      this.fetchProducts(
        this.$store.state.tweakwise?.tweakwiseLayeredNavigationAttributes || []
      );
    },
},

Solution

  • make computed property for state you want to watch, than create watch() for this prop. In watch you can react on computed property change.

    <template>
      <div v-for="product in products"></div>
    </template>
    <script>
    export default {
      data: {
        return {
          products: [],
        }
      },
      computed: {
        tweakwiseLayeredNavigationAttributes() {
          return this.$store.state.tweakwise.tweakwiseLayeredNavigationAttributes;
        },
      },
      watch: {
        // on every tweakwiseLayeredNavigationAttributes change we call fetchProducts
        tweakwiseLayeredNavigationAttributes: {
          handler(newValue, oldValue) {
            this.fetchProducts(newValue);
          },
          deep: true, // necessary for watching Arrays, Object
          immediate: true, // will be fired like inside mounted()
        }
      },
      methods: {
        async fetchProducts(params) {
          const products = await axios.get('/api', params);
          this.products = products;
        }
      }
    };
    </script>