18. Create selectors

In this section we will create selectors in NgRx which are a cornerstone piece of getting your NgRx architecture right.

1. Add selector file for spinner state

Selectors are methods used for obtaining slices of store state. @ngrx/store provides a few helper functions for optimising this selection. Selectors are a big deal to help get your architecture right and you can read more in the docs here https://github.com/ngrx/platform/blob/master/docs/store/selectors.mdarrow-up-right.

When using the createSelector and createFeatureSelectorfunctions @ngrx/store keeps track of the latest arguments in which your selector function was invoked. Because selectors are pure functionsarrow-up-right, the last result can be returned when the arguments match without re-invoking your selector function. This can provide performance benefits, particularly with selectors that perform expensive computation. This practice is known as memoizationarrow-up-right.

  • Make a spinner.selectors.ts file.

  • Make a getSpinnerState using createFeatureSelector, we can do this for other different feature state making it possible to join state slices together.

  • Make a getSpinner selector using the createSelector method to return just the boolean value of the isOn property.

src/app/state/spinner/spinner.selectors.ts
import { createFeatureSelector, createSelector } from '@ngrx/store';
import { State } from './spinner.reducer';

export const getSpinnerState = createFeatureSelector<State>('spinner');

export const getSpinner = createSelector(
  getSpinnerState,
  (state: State) => state.isOn
);

2. Use the new selector in our EventComponent

It is possible to see in this step how selectors clean our u=our code and make it easier for other developer son our team to know what they can get from the store.

  • Use the getSpinner selector versus our inline function where we "dot" into the property on the state tree we want.

Web Link: Link to the demo app running in StackBlitz

Last updated