1 year ago

#362520

test-img

meep meep

Nuxt / Vuex: use async getter in another computed property

Store / actions.js

export default {
  async fetchData(context, route) {
    const dataURL = `myUrl.json`;
    const response = await fetch(dataURL);
    const responseData = await response.json();
    let arr = [];

    if (!response.ok) {
      const error = new Error(responseData.message || 'Failed to fetch requests.');
      throw error;
    }

    // Commit arr to mutation
    arr = responseData;
    context.commit('addArr', arr);

  },
}

Store / mutations.js

export default{
  addArr(state, payload) {
    state.arr = payload;
  }
}

Store / state.js

export default () => ({
  arr: []
})

Store / getters.js

export default {
  getArr(state) {
    return state.arr;
  }
}

Vue / myComponent.vue

 <template>
        <div>
          <pre>
           THIS WORKS FINE
           {{getArr}}
          </pre>

          <pre>
           THIS WORKS FINE
            {{myArr1}}
          </pre>

          <pre>
           THIS WORKS FINE
           {{myArr2}}
          </pre>

         <pre>
           THIS WORKS FINE
           {{myArr2}}
         </pre>

         <div v-for="(item, index) in sortArr" :key="item.id">
           {{item.name}}
           ....
         </div>
  </div>
    </template>
    <script>
    import {mapGetters} from 'vuex';
    export default {
      name: "myComponent",
      computed: {
        ...mapGetters(['getArr']),
        myArr1() {
          return this.getArr;
        },
        myArr2() {
          return this.$store.getters.getArr;
        },
        sortArr() {
          const unsortedArr = this.$store.getters.getArr;
          // const unsortedArr = this.myArr1;
          // const unsortedArr = this.myArr2;
          
          // Does not work, always returns empty array 
          console.log(unsortedArr);

         let sortedArr = [];

          ....
          // unsortedArr gets now manipulated.. a lot of magic happens here.. 

          return sortedArr;
        },
      },
  methods: {
    async fetchData() {
      await this.$store.dispatch('fetchData');
    },
  },
  async created() {
    await this.fetchData; 
  },
    }
    </script>

I think a have a fundamental lack of understanding, how getters from vuex work.... I thought i could get my array from getters and work with it in my compoment. But it is not possible to assign the value of my getter to a variable and use it in another computed property or method.

Is there a better way to do this? What am i missing? And what would be the solution to use my sorted, manipulated list of items in my component?

Thank you!

javascript

vue.js

nuxt.js

vuex

computed-properties

0 Answers

Your Answer

Accepted video resources