Search code examples
javascriptangulartypescriptrxjsngrx

angular ngrx store Parameterized memoized selectors


I read this article https://blog.angularindepth.com/ngrx-parameterized-selector-e3f610529f8

And not found how to adapt to pass a params into my selectors

I tried pass a props object into my component to the selector.

[EDITED] answer with @Julius Dzidzevičius solution.

in component

this.store.pipe(select(fromRoot.selectors.getPreferences, 'myProps'))

in AppState

const rootSelectors = {
  layout: (state: AppState) => _.get(state, 'layout'),
}

export interface Selectors {
  getPreferences: MemoizedSelectorWithProps<AppState, string, Preference[]>;
}

export const selectors: Selectors = {
  getPreferences: createSelector(
      rootSelectors.layout,
      (state: LayoutState, props: string) 
=> layoutSelectors.preferences(state, props)) 
};

in state

export const layoutSelectors = {
  preferences: (state: LayoutState, props: string) => {
    return state.filter(item => item.name === props)
  },
};

If someone could tell me just how to adapt correctly this parameter. from component to selector through the memoized Selector.


Solution

  • Memoized selector parameters are held under props property. Here:

    (counter) // should be somewhere else but don't know how :(
    => layoutSelectors.preferences(counter))
    

    counter is a value that comes from rootSelectors.layout. Can't say whats behind it or what is your goal here, but to access props in selector:

    (counter, props) => layoutSelectors.preferences(props.counter))