2

I have selector to get all posts, actually all entities, now I want to get single post/entity. Should I filter the posts I get from 'getAllPosts' selector or create another one and how to do it ?

Here are my selectors:

export const getPostsState = createFeatureSelector<fromPosts.PostState>('posts');

export const selectAllPosts = createSelector(getPostsState, fromPosts.getAllPosts);
export const selectPostsEntities = createSelector(getPostsState, fromPosts.getAllPosts);
export const selectPostsIds = createSelector(getPostsState, fromPosts.getPostsIds);
export const selectTotal = createSelector(getPostsState, fromPosts.getPostsTotal);
export const selectPostId = createSelector(getPostsState, fromPosts.getSelectedPostId);

export const getSelectedPost = createSelector(selectPostsEntities, selectPostId, (entities, id) => entities[id]);

As you see I have getSelectedPostId and getSelectedPost selectors but I'm not sure how to use it, I tried to follow some tutorials but nothing helps..

Merim
  • 1,283
  • 2
  • 21
  • 36

1 Answers1

1

Maybe it is a bit late, but it might help someone out there. You are using the same entity adapter selector for both, the list of entries and the entities. And you do not define what you want to do with your selected data. The last argument of the createSelector function should always be a function having arguments which are directly related to the before mentioned selectors and should return some value (usually the argument itself or a modification of it).

export const selectAllPosts = createSelector(getPostsState, fromPosts.getAllPosts);
export const selectPostsEntities = createSelector(getPostsState, fromPosts.getAllPosts); // <-- see

But it should use the selectEntities instead of selectAll. Imagine you get the selectors from the entity adapter like this and that you have your custom ID selector implemented:

// NgRX entity selectors
const {
  selectIds,
  selectEntities,
  selectAll,
  selectTotal,
} = adapter.getSelectors();

// Custom selector for the selected ID (I guess you have it in the store) and 
// should be the equivalent of your `getSelectedPostId` selector.
const getSelectedId = createSelector(getState, state => state.id);

Then you can combine the selectEntities with the getSelectedId in the following way:

export const selectedEntity = createSelector(
  selectEntities,
  getSelectedId,
  (entities, id) => entities[id]
);

Personally I prefer to import the adapter in the selectors so that you can simply use the above statement in your reducer and make all of the adapter related selectors available where they are needed.

Felix Lemke
  • 6,189
  • 3
  • 40
  • 67