Alex Dn
Alex Dn

Reputation: 5553

NgRx parent selector static params

Let's say I have selector which receives props:

export const selectTaskById = createSelector(
  selectCoreState,
  (state, props: { id: TaskKey }) => state?.tasks[props.id] || null
);

Then I have another selector, which doesn't receives props, but it needs to use the peace of data from above selector, by providing it hardcoded id:

export const selectGeneralTask = createSelector(
  selectTaskById, // -- Here I want to pass hardcoded props with {id: 'generalTask'}
  (state) => state
);

I searched through SO and internet and didn't found a solution how I can achieve this.

In bottom line, I would like to find a way, how I can make kind of "abstraction" on selectors, without having a need to know "id" in every place where I need the info for specific task.

UPDATE
As for now, the only solution that I found is as follows:
I added one more selector:

export const selectRootState = (state: AppState) => state;

Then, used it in selectGeneralTask:

export const selectGeneralTask = createSelector(
  selectRootState,
  (state) => selectTaskById(state, {id: 'generalTask'})
);

If someone has alternative way to solve it, I would very glad to hear it.

Upvotes: 0

Views: 149

Answers (1)

timdeschryver
timdeschryver

Reputation: 15507

You can create a factory selector:

export const selectTaskById = (id) => createSelector(
  selectCoreState,
  (state) => state?.tasks[id] || null
);

export const selectGeneralTask = createSelector(
  selectTaskById('generalTask'),
  (state) => state
);

Upvotes: 1

Related Questions