Search code examples
vue.jsvuexundefined

How to catch an empty Vuex Store state but have a computed property react to it when initialized


I am working on a Project in Vue Storefront with Vuex.

I have the following element to sort products in my webshop

      <SfSelect
        class="navbar__select sort-by"
        ref="SortBy"
        :selected="selectedSorting"
        @change="setSortingAttribute"
      >
        <SfSelectOption
          v-for="attribute in getSortingAttributes"
          :key="attribute.id"
          :value="attribute.title"
          class="sort-by__option"
          @click="setSelectedSortingAttribute(attribute)"
        >
          {{ attribute.title }}
        </SfSelectOption>
      </SfSelect>

Where v-for="attribute in getSortingAttributes" does a for-loop on all available filters.

These filters are called from the Vuex Store State via the following computed property:

getSortingAttributes: function () {
  if (store.state.tweakwise.tweakwiseLayeredNavigationAttributes
      .properties.sortfields
  ) {
    var tempSortAttributes =
      this.$store.state.tweakwise.tweakwiseLayeredNavigationAttributes
        .properties.sortfields;

    return tempSortAttributes;
  }
},

This array is in the Vuex Store (tweakwiseLayeredNavigationAttributes.properties.sortfields) where .poperties is an object in the array. The array is filled via an API call, this call is trigged via a Mount() in the same class as the SfSelect function, which I mentioned above.

Eventhough i added an if-statement to the getSortingAttributes to prevent it from calling undefined data and made it a computed property (to call it as soon as the data is available), I still get the following error:

Error during render : CategoryX/SubcategoryY/

TypeError: Cannot read property 'sortfields' of undefined


Solution

  • You should add safeguard(s) to your code - either using the new nullish coalescing operator or the old-school boolean OR:

    getSortingAttributes() 
    {
      return this.$store.state.tweakwise?.tweakwiseLayeredNavigationAttributes?.properties?.sortfields || [];
    },
    
    
    getSortingAttributes() 
    {
      return (((this.$store.state.tweakwise || {}).tweakwiseLayeredNavigationAttributes || {}).properties || {}).sortfields || [];
    },