Entity State

Define the initial entity state

In our example we are building the state for the Customer entity. As such, we've created a new customer.state.ts file located at src/app/state/customer.state.ts.

customer.state.ts
import { Action } from '@ngrx/store';
import { buildState, IEntityState } from '@briebug/ngrx-auto-entity';
import { Customer } from '../models/customer.model';

export const { initialState, selectors, facade: CustomerFacadeBase } = buildState(Customer);

export const {
  selectAll: allCustomers
} = selectors;

export function customerReducer(state = initialState): IEntityState<Customer> {
  return state;
}

Import the buildState function from the ngrx-auto-entity module. This function builds the initial state and selectors for each entity. Call the function by passing in the Customer entity class (note, the class must be passed in!) We use object destructuring on the return type access the initialState , selectors and facade base class from the result of buildState.

We can now further destructure the selectors object to map each type of standard selector to model-specific names for import into other modules:

  • selectAll selects the Array of entities

  • selectEntities selects the Dictionary of entities

  • selectIds selects the Array of entity identifiers (keys)

  • selectTotal selects the number of entities

Note that retrieving and exporting the selectors are optional if you extract the facade. The facade base class generated by buildState fully encapsulates all of the functionality you will need to interact with your entity state, and we generally recommend only using the facade. Demonstration of how to access selectors directly, such as in the event that you may need to create your own custom selectors, is simply for completeness here.

Finally, we define the customerReducer function. The reducer function accepts two arguments: state, which defaults to the initialState, and the action.

Last updated