0
votes

I've been struggling with the .find() method in a vuex getter.

I set up a store with a list in state (pages)

// state.js
const state = {
  pages: [{id:1, content:"Page 1"}, {id:2, content:"Page 2"}]
};

And a getter with a find method like in this post: Reference

// getters.js
const getters = {
  indexPage: state => {
    let indexPage = state.pages.find(function(page) { // same error with arrow function
      return page.id === 1;
    });
    return indexPage !== undefined ? indexPage : null;
  }
}

I expected to return the first object but after I map the getter (with mapGetters) in a component it throws this error.

TypeError: "page is undefined"

Also I tried the same code with .filter() method (which returns an array) but it does work without any errors. This code works:

const getters = {
  indexPage: state => {
    let indexPage = state.pages.filter(page => page.id === 1);
    return indexPage[0];
  }
}
1
What do you get when you run console.log(state.pages);mwilson
The list, pages. But funny thing, it fix it (although there is a console statement and ESLint is going crazy). Edit: I mean by fix it, throws no error and is passing the data to the component.Seba

1 Answers

1
votes

try with:

const getters = {
  indexPage: state => page => state.pages.find(p => p.id === page)
}

UPDATE: using mapGetters

const store = new Vuex.Store({
  state: {
    pages: [
      {id:1, content:"Page 1"}, 
      {id:2, content:"Page 2"}
    ]
  },
  getters: {
    indexPage: state => page => state.pages.find(p => p.id === page)
  }
})

const mapGetters = Vuex.mapGetters

new Vue({
  el: '#app',
  store,
  mounted () {
    console.log(this.indexPage(1))
  },
  computed: {
    ...mapGetters([
      'indexPage'
    ])
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://unpkg.com/vuex"></script>
<div id="app"></div>