1

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];
  }
}
2
  • 1
    What do you get when you run console.log(state.pages); Commented Dec 24, 2019 at 0:58
  • 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. Commented Dec 24, 2019 at 1:02

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

8 Comments

Same result. Was the first thing I tried and led me to that spaghetti code
how are u calling your getter?
Then indexPage will return a Function instead of a page right?
there will return the object with the same id that the page param
Yes, then i pass the id (1). Return undefined.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.