angularngrxngrx-storengrx-selectors

How to get a different state in your selector or how to use a selector inside of a selector


I have the following selector

const getLinkFeatureState = createFeatureSelector<ILinkReducer>('link');

export const getLinkIsLinkDtoPricesDeliveryTimesSome = (index: number) => createSelector(
  getLinkFeatureState,
  state => state.linkDto.prices[index].deliveryTimes.some(d => d.iso == state.???)
)

now i would like use the the state of my other reducer

export interface ISelectedLanguageReducer {
  language: ILanguage;
  isLanguageSuccess: boolean;
}
const selectedLanguageInitial: ISelectedLanguageReducer = {
  language: {
    country: '',
    value: '',
    selected: false
  },
  isLanguageSuccess: false
}

with the following selector

const getSelectedLanguageFeatureState = createFeatureSelector<ISelectedLanguageReducer>('selectedLanguage');
export const getSelectedLanguageLanguage = createSelector(
  getSelectedLanguageFeatureState,
  state => state.language
);

Is there any way to get the selected language inside of 'link' selector or to use a selector inside of a selector?


Solution

  • You can achieve that by adding the other selector directly within createSelector function, like the following:

    export const getLinkIsLinkDtoPricesDeliveryTimesSome = (index: number) =>
        createSelector(getLinkFeatureState, getSelectedLanguageLanguage, (state, selectedLang) =>
            // >>> you can use the selectedLang here
            state.linkDto.prices[index].deliveryTimes.some((d) => d.iso == state.???)
        );
    

    Make sure another state is initialized within the module before using it.

    You can check this overload of createSelector at Using selectors for multiple pieces of state.