Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngrx: how to pass parameters to selector inside createSelector method

Tags:

angular

ngrx

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?

like image 451
user3429127 Avatar asked Nov 29 '18 19:11

user3429127


People also ask

Can I use selector in effect NgRx?

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.

What is Memoized selector NgRx?

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.

How do NgRx selectors work?

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.


1 Answers

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.

like image 96
DeborahK Avatar answered Sep 28 '22 01:09

DeborahK