Skip to content

Instantly share code, notes, and snippets.

@rainerhahnekamp
Created October 21, 2022 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rainerhahnekamp/af61018c575e2351bfd77ba44e1e545c to your computer and use it in GitHub Desktop.
Save rainerhahnekamp/af61018c575e2351bfd77ba44e1e545c to your computer and use it in GitHub Desktop.
NgRx selector with customized equal function
import { isEqual } from 'lodash';
import {
createFeatureSelector,
createSelector,
createSelectorFactory,
defaultMemoize,
} from '@ngrx/store';
import * as fromFlightBooking from './flight-booking.reducer';
export const selectFlightBookingState = createFeatureSelector<
fromFlightBooking.State
>(fromFlightBooking.flightBookingFeatureKey);
export const selectFlights = createSelector(
selectFlightBookingState,
(state) => state.flights
);
export const selectFirstFlight = createSelector(selectFlights, (flights) => {
console.log('selectFirstFlight');
if (flights.length) {
return flights[0];
} else {
return null;
}
});
// https://github.com/ngrx/platform/issues/1157
const customMemoizer = (aFn) => defaultMemoize(aFn, isEqual);
const createDeepEqualSelector = createSelectorFactory(customMemoizer);
export const flightName = createSelector(selectFirstFlight, (flight) => {
console.log('selectFlightName');
return flight ? { name: flight.from } : '';
});
export const heavyCalculation = createDeepEqualSelector(flightName, () => {
console.log('doing heavy calculation');
return true;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment