Skip to content

Derived state where a selector depends on the results of another selector. #3273

Answered by david-shortman
Quraian asked this question in Q&A
Discussion options

You must be logged in to vote

@Quraian, By delaying the collection of the id param until later, you can use the result of selectQueryParam('id") to select an entity by id!

export const selectByIdFunc = createSelector(
  selectEntities,
  //             👇 we return a function that takes in an id and returns the correct entity
  (entities) => (id: string) => entities.items.find((entity) => entity.id === id)
);

export const selectEntity = createSelector(
  routerSelectors.selectQueryParam('id'),
  selectByIdFunc,
  (id, getEntityById) => getEntityById(id));

Memoization still works properly, as selectByIdFunc will only change when entities change, and selectEntity will only change when the query param for "id" changes or…

Replies: 2 comments 5 replies

Comment options

You must be logged in to vote
3 replies
@Quraian
Comment options

@markostanimirovic
Comment options

@Quraian
Comment options

Comment options

You must be logged in to vote
2 replies
@david-shortman
Comment options

@Quraian
Comment options

Answer selected by Quraian
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants