Simplify your reducers with @ngrx/entity

NgRx team works hard on reducing the boilerplate. That’s one of the reasons of building such a library. But there are more!

You possibly deal with collections in your store, and maintaining your store data with large and complex collections of entities might give you a headache, not to mention the boilerplate code it brings to your reducers.

@ngrx/entity is there for the rescue to simplify your reducers and domain models.

Entity State

After setting up your entity adapter, your entity state will look like the following in your store.

interface EntityState<T> {

ids: string[];

entities: { [id: string]: T };

}

There are a couple of reasons for maintaining a dictionary of entities and a list of ids in your entity state:

In order to keep your collection sorted along with having a dictionary, you need an ordered list. That’s why ids array is part of the entity state. Lookup actions are expensive operations most of the times if you maintain your data as a list. Using a dictionary for your entities is much faster compared to searching through an array.

CUD operations (Create, Update, Delete)

Entity adapter brings many useful methods for your CUD needs in the store.

Take a look at the following in-app events example of mine, to see available operations, as well as different use cases with partial changes object.

Entity adapter and some of the CUD operations — reducer

Default Selectors

Your entity adapter instance exports 4 useful selectors for you. You can export them in your selectors file, along with your custom ones if needed.

export const {

selectIds,

selectEntities,

selectAll,

selectTotal,

} = yourEntityAdapter.getSelectors();

Use ngrx-data if you’ve too many domain models

If you want to take reducing the boilerplate code of your domain models to another level, you might want to take a look at ngrx-data library. It’s not part of official @ngrx/platform just yet, but they announced that it will be soon.

It’s not an alternative for ngrx, but instead it’s an additional flavour for it to extend managing domain models. As it’s stated on their documentation:

Many applications have substantial domain models with 10s or 100s of entity types such as Customer, Order, LineItem, Product, and User. In plain ngrx, to create, retrieve, update, and delete (CRUD) data for every entity type is an overwhelming task. You’re writing actions, action-creators, reducers, effects, dispatchers, and selectors as well as the HTTP GET, PUT, POST, and DELETE methods for each entity type. In even a small model, this is a ton of repetitive code to create, maintain, and test. The ngrx-data library is one way to stay on the ngrx path while radically reducing the “boilerplate” necessary to manage entities with ngrx.