reselect icon indicating copy to clipboard operation
reselect copied to clipboard

[Question] Is this the way I should reselect an article and the articles?

Open cristian-sima opened this issue 10 years ago • 3 comments

Let's take for instance this code


const visibleIDsListSelector = (state) => state.companyArticles.visibleIDs.IDs;
const byIDsMapSelector = (state) => state.companyArticles.byID;

export const getArticle = createSelector(
  byIDsMapSelector,
  (theMap) => (id) => theMap.get(String(id))
);

export const getVisibleArticles = createSelector(
  visibleIDsListSelector,
  getArticle,
  (IDs : any, articleSelector) => IDs.map((id) => articleSelector(id))
);

So, I want to return 2 functions which:

  1. getArticle returns the article by id
  2. getVisibleArticles returns all the visible articles (using their IDs)

Do I do it in the right way? I feel that by passing getArticle as a function and then using it inside the getVisibleArticles I feel is not the proper way.

Note:

state.companyArticles.visibleIDs.IDs is a ImmutableJS.List state.companyArticles.byID is a ImmutableJS.Map

cristian-sima avatar Sep 10 '16 17:09 cristian-sima

I've only looked at it quickly, but I'm not sure using getArticle as an input selector to getVisibleArticles gives you any benefit. Remember that createSelector only memoizes its last call, so mapping articleSelector across a list is going to result in a cache miss each time.

Does something like this (not tested) will work for you?

const visibleIDsListSelector = (state) => state.companyArticles.visibleIDs.IDs;
const byIDsMapSelector = (state) => state.companyArticles.byID;

export const getArticle = (state, id) => byIDsMapSelector(state).get(id);

export const getVisibleArticles = createSelector(
  visibleIDsListSelector,
  byIDsMapSelector,
  (IDList : any, IDMap) => IDList.map(id => IDMap.get(String(id)))
);

ellbee avatar Sep 11 '16 12:09 ellbee

Nice. Let me check

cristian-sima avatar Sep 12 '16 14:09 cristian-sima

Great answer :) Thanks

cristian-sima avatar Sep 12 '16 15:09 cristian-sima