I have a very simple state in my store:
const state = { records: [1,2,3], };
I have a selector for records:
export const getRecords = createSelector(getState, (state: State) => state.records));
And what I want now is to have separate selectors for fetching each record by index. For this purpose I want to create one generic selector with props in this way:
export const getRecordByIndex = createSelector( getRecords, (state: State, { index }) => state.records[index]), );
And after that create a couple of specific selectors e. g.:
export const getFirstRecord = createSelector( getRecordByIndex(/* somehow pass index = 0 to this selector */), (firstRecord) => firstRecord), );
But I didn't find any mention how to pass parameters to selectors with props when we use them inside createSelector method. Is it possible?
Create Menu Selectors Similar to what you did with Actions, let's update the application to get data required by the components using NgRx Selectors. You can use Selectors by injecting NgRx's Store and calling it's select function passing in the selector's name, which returns the slice of the state that we need.
Because selectors are pure functions, the last result can be returned when the arguments match without reinvoking your selector function. This can provide performance benefits, particularly with selectors that perform expensive computation. This practice is known as memoization.
Selectors are basically the NgRx change detection mechanism. When a state is updated, NgRx doesn't do any comparison between old state and the new state to figure out what observables to trigger. It simply sends a new state through all top level selectors.
From this blog post: https://timdeschryver.dev/blog/parameterized-selectors
As of NgRx 6.1 selectors also accepts an extra props argument. Which means you can now define a selector as the following:
export const getCount = createSelector( getCounterValue, (counter, props) => counter * props.multiply ); this.counter = this.store.pipe( select(fromRoot.getCount, { multiply: 2 }) );
Ah ... but rereading your question, you are asking then how to build another selector that uses this selector? The above-linked article suggests building a factory function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With