Created
October 21, 2022 11:03
-
-
Save rainerhahnekamp/af61018c575e2351bfd77ba44e1e545c to your computer and use it in GitHub Desktop.
NgRx selector with customized equal function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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