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];
}
}
console.log(state.pages);
– mwilson