How to make a getter function?

In the vault vuex have an array of categories and an array of posts with the id of the category to which it belongs:
{
 posts: [
 {id: 1, catId: 1, title: 'Foo'},
//...
],
 categories: [
 {id: 1, title: 'CatFoo'}
]
}


During the application, you will need to get an array of posts for a specific category. How to do it using vuex getter? To have cached the result and fails, the filter array each time.
April 3rd 20 at 17:26
1 answer
April 3rd 20 at 17:28
Solution
At the end he wrote something like that:

getters: {
 getPostsByCategory(state) {
 const map = new Map();
 state.posts; // getter Needs to be recalculated when changing state.posts

 return (catId) => {
 if (map.has(catId)) {
 return map.get(catId);
}

 let posts = state.posts.filter(p => p.catId === catId);
 map.set(catId, post);


 return posts;
};
}
}


How it works:
The getter returns not a result but a function. This function filters the posts, and through-circuit caches the result. If any other component requires a list of posts in the same category — Eni will be returned from the cache.

When you change state.posts — this internal cache is flushed and the list of posts will be created again

Find more questions by tags Vue.js