bartosz.baczek
bartosz.baczek

Reputation: 1516

NGRX - combine selectors with props

How do I combine reducers, when one of them needs props?

I have following model:

interface Device {
  id: string;
  data: IDeviceData;
}

and DeviceReducer that looks as follow:

import { EntityState, EntityAdapter, createEntityAdapter } from '@ngrx/entity';
import { Device } from '../model/device';
import { SubnetBrowserApiActions } from 'src/app/explorer/actions';

export interface State extends EntityState<Device> { }

export const adapter: EntityAdapter<Device> = createEntityAdapter<Device>();

export const initialState: State = adapter.getInitialState();

export function reducer(
  state = initialState,
  action:
    | SubnetBrowserApiActions.SubnetBrowserApiActionsUnion
): State {
  switch (action.type) {
    case SubnetBrowserApiActions.SubnetBrowserApiActionTypes.LoadEntriesSucces: {
      return adapter.upsertMany(action.payload.entries, state);
    }

    default: {
      return state;
    }
  }
}

const {
  selectAll,
} = adapter.getSelectors();

export const getAllDevices = selectAll;

In my other reducer, when I want to select devices using an array of ids I use this code:

export const getVisibleDrives = createSelector(
  [fromRoot.getAllDevices, getVisibleDrivesSerialNumbers],
  (devices, visibleDevicesIds) =>
    devices.filter((device) => onlineDevicesIds.includes(device.serialNumber)),
);

This code is very repetitive, so I'd like to add add parametrized selector that will return just these drives, that have id in array that I pass as prop. What I tried to do looks as follows:

Additional selector in DeviceReduced

export const getDrivesWithIds = (ids: string[]) => createSelector(
  getAllDevices,
  devices => devices.filter(device => ids.includes(device.id))
);

And then combine them in the following way:

export const getVisibleDrives = createSelector(
  getVisibleDrivesSerialNumbers,
  (ids) => fromRoot.getDrivesWithIds
);

Issue here is that the returned type of this selector is

(ids: string[]) => MemoizedSelector<State, Device[]>

Which makes it impossible for me to do anything useful with this selector. As an example I'd like to filter this list by keyword, and I am not able to use filter method on it:

Example usage

export const getFilteredVisibleDrives = createSelector(
  [getVisibleDrives, getKeywordFilterValue],
  (visibleDrives, keywordFilter) => {
    return visibleDrives
      .filter(drive => // in this line there is an error: Property 'filter' does not exist on type '(ids: string[]) => MemoizedSelector<State, Device[]>'
        drive.ipAddress.toLowerCase().includes(keywordFilter.toLowerCase()) ||
        drive.type.toLowerCase().includes(keywordFilter.toLowerCase()) ||
        drive.userText.toLowerCase().includes(keywordFilter.toLowerCase())
      );
  },
);

Upvotes: 4

Views: 9903

Answers (1)

timdeschryver
timdeschryver

Reputation: 15505

See my post NgRx: Parameterized selectors for more info.

Update: NgRx v13+

Selector with props are deprecated, use selector factories instead:

Selector:

export const getCount = (props: {id: number, multiply:number}) =>   
  createSelector(     
    (state) => state.counter[props.id],     
    (counter) => counter * props.multiply
  );

Component:

this.counter2 = this.store.pipe(
  select(fromRoot.getCount({ id: 'counter2', multiply: 2 })
);   
this.counter4 = this.store.pipe(
  select(fromRoot.getCount({ id: 'counter4', multiply: 4 })
);

Deprecated

Selector:

export const getCount = () =>   
  createSelector(     
    (state, props) => state.counter[props.id],     
    (counter, props) => counter * props.multiply
  );

Component:

this.counter2 = this.store.pipe(
  select(fromRoot.getCount(), { id: 'counter2', multiply: 2 })
);   
this.counter4 = this.store.pipe(
  select(fromRoot.getCount(), { id: 'counter4', multiply: 4 })
);

Upvotes: 7

Related Questions