Search code examples
vue.jsvuejs2vuex

Why do i get undefined when passing parameter to mapped getter?


I have some getters set up, you pass them an id and they return the relevent data. So i've mapped these into a component, however when passing a param the param is undefined.

Component:

<template>
    <div>
        <h1>{{ category.name }}</h1>
    </div>
</template>

<script>
    import { mapGetters } from 'vuex'

    export default {
        props: ['id'],

        computed: mapGetters({
            subCategories: ['categories/getSubcategories'](this.id),
            category: ['categories/getCategory'](this.id)
        })
    }
</script>

Getter:

getCategory: (state, id) => {
    return state.categories.filter(category => category.id === id);
},

The error being:

Cannot read property 'id' of undefined

If I pass it a hard coded parameter, e.g category: ['categories/getCategory'](106) then I get:

['categories/getCategory'] is not a function

Where am I going wrong here?

EDIT: Here's my store: console.log(this.$store)


Solution

  • According to this GitHub issue, it seems what you need is to return a function in your getters and then call the method in the computed property, i.e. your getter:

    getCategory: state => {
      return id => state.categories.filter(category => category.id === id);
    }
    

    And then in computed property:

    computed: {
      ...mapGetters([
        'categories/getSubcategories', 
        'categories/getCategory'
      ]),
      subCategories () {
        return this['categories/getSubcategories'](this.id)
      },
      category () {
        return this['categories/getCategory'](this.id)
      }
    }