Recently, I've been facing some challenges while using the .find()
method within a vuex getter.
I initialized a store with a list under state (pages)
// state.js
const state = {
pages: [{id:1, content:"Page 1"}, {id:2, content:"Page 2"}]
};
In my getter, I tried implementing a find method similar to what was discussed in this post: Reference
// getters.js
const getters = {
indexPage: state => {
let indexPage = state.pages.find(function(page) { // encountered the same issue with arrow function
return page.id === 1;
});
return indexPage !== undefined ? indexPage : null;
}
}
I expected to retrieve the first object but upon mapping the getter (using mapGetters) in a component, it led to the following error:
TypeError: "page is undefined"
In an attempt to resolve this issue, I also experimented with the .filter()
method (which returns an array). Surprisingly, it worked flawlessly without any errors. The modified code snippet looks like this:
const getters = {
indexPage: state => {
let indexPage = state.pages.filter(page => page.id === 1);
return indexPage[0];
}
}