Reputation: 6255
I have a redux state containing posts, which I store as a single object with the following shape:
posts: {
1: { isPublic: true, content: 'foo' },
2: { isPublic: true, content: 'bar' },
3: { isPublic: false, content: 'foobar' },
}
I'm fetching the state using reselect from my component, and I have created 2 selectors for that:
const getPostsEntities = (state) => state.posts;
export const getPosts = createSelector(
[ getPostsEntities ],
(posts) => Object.keys(posts).map( id => posts[id])
);
export const getPublicPosts= createSelector(
[ getPostsEntities ],
(posts) => Object.keys(posts).map( id => posts[id]).filter( post => post.isPublic )
);
My doubt is about this part which seems redundant in any selector
(posts) => Object.keys(posts).map( id => posts[id])
I thought about having the getPostsEntities
return directly the array, but I'm having some issue understanding what's the best practice
Upvotes: 0
Views: 79
Reputation: 42170
As mentioned by @HMR, you can use one reselect selector inside another. So getPublicPosts
can be based on the memoized results from getPosts
. You can also use Object.values()
instead of Object.keys()
.
const getPostsEntities = (state: State) => state.posts;
export const getPosts = createSelector(
[ getPostsEntities ],
(posts) => Object.values(posts)
);
export const getPublicPosts = createSelector(
[ getPosts ],
(posts) => posts.filter(post => post.isPublic)
);
Upvotes: 1