Derived state where a selector depends on the results of another selector. #3273
-
I am trying to figure out how to do something like the following: export const selectById = (id: string) =>
createSelector(selectEntities, (entities) => entities.items.find((entity) => entity.id === id));
export const selectEntity = createSelector(routerSelectors.selectQueryParam('id'), selectById, (_, entity) => entity); So, basically one selector depends on the result of a previous selector, how to do this in a clean way? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
You can do the following: export const selectEntityFromRoute = createSelector(
selectEntities,
routerSelectors.selectQueryParam('id'),
(entities, id) => entities.find((entity) => entity.id === id)
); |
Beta Was this translation helpful? Give feedback.
-
@Quraian, By delaying the collection of the 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 |
Beta Was this translation helpful? Give feedback.
@Quraian, By delaying the collection of the
id
param until later, you can use the result ofselectQueryParam('id")
to select an entity by id!Memoization still works properly, as
selectByIdFunc
will only change whenentities
change, andselectEntity
will only change when the query param for "id" changes or…