Search code examples
vuejs2vuexnuxt.js

Nuxt + Vuex mapGetters value is always undefined


I'm using VueX with Nuxt.JS so let's suppose the following code in the file store/search.js:

    export const state = () => ({
    results: null
});

export const mutations = {
    setResults(state, { results }) {
        state.results = results;
    }
};

export const actions = {
    startSearch({ commit, dispatch }, { type, filters }) {
        commit("setResults", { type, filters });
    }
};

export const getters = {
    results: state => state.results
};

Now in my component results.vue, under the computed property I have something like this:

<template>
<button @click="handleSearch">Search</button>
<div v-if="results && results.length" class="results" >
<div v-for="item in results" :key="item.id">

          {{item}}

        </div>
</div>
</template>

<script>

import { mapActions, mapGetters } from "vuex";
 data() {
    return {
      selected_type: null,
      filters: null
    };
  },
methods: {
    setType(type) {
      this.selected_type = type;
      this.handleSearch();
    },
    setFilters(filters) {
      this.filters = filters;
    },
    handleSearch() {
      this.startSearch({ type: this.selected_type, filters: this.filters });
    },
    ...mapActions("search", {
      startSearch: "startSearch"
    })
  },
computed: {
...mapGetters("search", {
      results: "results"
    })
}
</script>

My question is: why the item in the for loop (in the template section) always return undefined ?

Thank you very much for your answers.


Solution

  • So far, I found it: in computed should be an array, not an object so:

    ...mapGetters("search", [
          "results"
    ]
    
    // Now results is populated.