Simplify Your Angular Code with NgRx Entities: Why I love NgRx Entities
In the summer, I refreshed my NgRx skills by building a small application to handle my favorite places. During that process, I enjoyed NgRx because I had real control over the state of my app.
One thing that caused a lot of noise was the number of selectors and actions to define for CRUD operations. In my personal project, it wasn't too much trouble, but when I was building a large application with many slices and sections, along with selectors and reducers, the code became harder to maintain.
For example, writing actions for success, error, update, and delete, along with selectors for each operation, increased the complexity and required more testing.
That's where NgRx Entities come in. NgRx Entities reduce boilerplate code, simplify testing, speed up delivery times, and keep the codebase more maintainable. In this article, I'll walk you through refactoring the state management of places in my project using NgRx Entities to simplify CRUD logic.
What and Why NgRx Entities?
Before diving into code, let's first understand what NgRx Entities are and why you should consider using them.
What is @NgRx/Entities
NgRx Entities is an extension of NgRx that simplifies working with data collections. It provides a set of utilities that make it easy to perform operations like adding, updating, and removing entities from the state, as well as selecting entities from the store.
Why Do I Need to Move to NgRx Entities?
When building CRUD operations for collections, manually writing methods in the reducer and creating repetitive selectors for each operation can be tedious and error-prone. NgRx Entities offloads much of this responsibility, reducing the amount of code you need to write and maintain. By minimizing boilerplate code, NgRx Entities helps lower technical debt and simplify state management in larger applications.
How Does It Work?
NgRx Entities provides tools such as EntityState, EntityAdapter, and predefined selectors to streamline working with collections.
EntityState
The EntityState interface is the core of NgRx Entities. It stores the collection of entities using two key properties:
ids
: an array of entity IDs.entities
: a dictionary where each entity is stored by its ID.
interface EntityState<V> {
ids: string[] | number[];
entities: { [id: string | id: number]: V };
}
Read more about Entity State
EntityAdapter
The EntityAdapter is created using the createEntityAdapter
function. It provides many helper methods for managing entities in the state, such as adding, updating, and removing entities. Additionally, you can configure how the entity is identified and sorted.
export const adapter: EntityAdapter<Place> = createEntityAdapter<Place>();
The EntityAdapter also allows you to define how entities are identified (selectId
) and how the collection should be sorted using the sortComparer
.
Read more about
EntityAdapter
Now that we understand the basics, let's see how we can refactor the state management of places in our application using NgRx Entities
Setup Project
First, clone the repository from the previous article and switch to the branch that has the basic CRUD setup:
git clone https://github.com/danywalls/start-with-ngrx.git
git checkout crud-ngrx
cd start-with-ngrx
💡This article is part of my series on learning NgRx. If you want to follow along, please check it out.
https://www.danywalls.com/understanding-when-and-why-to-implement-ngrx-in-angular
https://www.danywalls.com/how-to-debug-ngrx-using-redux-devtools
https://www.danywalls.com/how-to-implement-actioncreationgroup-in-ngrx
https://www.danywalls.com/how-to-use-ngrx-selectors-in-angular
https://danywalls.com/when-to-use-concatmap-mergemap-switchmap-and-exhaustmap-operators-in-building-a-crud-with-ngrx
https://danywalls.com/handling-router-url-parameters-using-ngrx-router-store
This branch contains the setup where NgRx is already installed, and MockAPI.io is configured for API calls.
Our goal is to use NgRx entities to manage places, refactor actions for CRUD operations, update the reducer to simplify it using adapter operations like adding, updating, and deleting places, use selectors to retrieve the list of places from the store.
Installing NgRx Entities
First, install the project dependencies with npm i
, and then add NgRx Entities using schematics by running ng add @ngrx/entity
.
npm i
ng add @ngrx/entity
Perfect, we are ready to start our refactor!
Refactoring the State
In the previous version of the project, we manually defined arrays and reducers to manage the state. With NgRx Entities, we let the adapter manage the collection logic for us.
First, open places.state.ts
and refactor the PlacesState
to extend from EntityState<Place>
.
export type PlacesState = {
placeSelected: Place | undefined;
loading: boolean;
error: string | undefined;
} & EntityState<Place>;
Next, initialize the entity adapter for our Place
entity using createEntityAdapter
:
const adapter: EntityAdapter<Place> = createEntityAdapter<Place>();
Finally, replace the manual initialState
with the one provided by the adapter using getInitialState
:
export const placesInitialState = adapter.getInitialState({
error: '',
loading: false,
placeSelected: undefined,
});
We've refactored the state to use EntityState and initialized the EntityAdapter to handle the list of places automatically.
let's move to update the actions to use NgRx Entities.
Refactoring the Actions
In the previous articles, I manually handled updates and modifications to entities. Now, we will use NgRx Entities to handle partial updates using Update<T>
.
In places.actions.ts
, we update the Update Place
action to use Update<Place>
, which allows us to modify only part of an entity:
import { Update } from '@ngrx/entity';
export const PlacesPageActions = createActionGroup({
source: 'Places',
events: {
'Load Places': emptyProps(),
'Add Place': props<{ place: Place }>(),
'Update Place': props<{ update: Update<Place> }>(), // Use Update<Place>
'Delete Place': props<{ id: string }>(),
'Select Place': props<{ place: Place }>(),
'UnSelect Place': emptyProps(),
},
});
Perfect, we updated the actions to work with NgRx Entities, using the Update
type to simplify handling updates. It's time to see how this impacts the reducer and refactor it to use the entity adapter methods for operations like adding, updating, and removing places.
Refactoring the Reducer
The reducer is where NgRx Entities really shines. Instead of writing manual logic for adding, updating, and deleting places, we now use methods provided by the entity adapter.
Here’s how we can simplify the reducer:
import { createReducer, on } from '@ngrx/store';
import { adapter, placesInitialState } from './places.state';
import { PlacesApiActions, PlacesPageActions } from './places.actions';
export const placesReducer = createReducer(
placesInitialState,
on(PlacesPageActions.loadPlaces, (state) => ({
...state,
loading: true,
})),
on(PlacesApiActions.loadSuccess, (state, { places }) =>
adapter.setAll(places, { ...state, loading: false })
),
on(PlacesApiActions.loadFailure, (state, { message }) => ({
...state,
loading: false,
error: message,
})),
on(PlacesPageActions.addPlace, (state, { place }) =>
adapter.addOne(place, state)
),
on(PlacesPageActions.updatePlace, (state, { update }) =>
adapter.updateOne(update, state)
),
on(PlacesPageActions.deletePlace, (state, { id }) =>
adapter.removeOne(id, state)
)
);
We’ve used methods like addOne
, updateOne
, removeOne
, and setAll
from the adapter to handle entities in the state.
Other useful methods include:
addMany
: Adds multiple entities.removeMany
: Removes multiple entities by ID.upsertOne
: Adds or updates an entity based on its existence.
Read more about reducer methods in the
EntityAdapter
.
With the state, actions, and reducers refactored, we’ll now refactor the selectors to take advantage of NgRx Entities’ predefined selectors.
Refactoring the Selectors
NgRx Entities provides a set of predefined selectors that make querying the store much easier. I will use selectors like selectAll
, selectEntities
, and selectIds
directly from the adapter.
Here’s how we refactor the selectors in places.selectors.ts
:
import { createFeatureSelector } from '@ngrx/store';
import { adapter, PlacesState } from './places.state';
const selectPlaceState = createFeatureSelector<PlacesState>('places');
const { selectAll, selectEntities, selectIds, selectTotal } = adapter.getSelectors(selectPlaceState);
These built-in selectors significantly reduce the need to manually create selectors for accessing state.
After refactoring the selectors to use the predefined ones, reducing the need to manually define my selectors, it is time to update our form components to reflect these changes and use the new state and actions.
Updating the Form Components
Now that we have the state, actions, and reducers refactored, we need to update the form components to reflect these changes.
For example, in PlaceFormComponent
, we can update the save
method to use the Update<Place>
type when saving changes:
import { Component, inject } from '@angular/core';
import { Store } from '@ngrx/store';
import { FormsModule } from '@angular/forms';
import { AsyncPipe } from '@angular/common';
import { selectSelectedPlace } from '../../pages/places/state/places.selectors';
import { PlacesPageActions } from '../../pages/places/state/places.actions';
import { Place } from '../../entities/place.model';
@Component({
selector: 'app-place-form',
standalone: true,
imports: [FormsModule, AsyncPipe],
templateUrl: './place-form.component.html',
styleUrls: ['./place-form.component.scss'],
})
export class PlaceFormComponent {
store = inject(Store);
placeSelected$ = this.store.select(selectSelectedPlace);
delete(id: string) {
this.store.dispatch(PlacesPageActions.deletePlace({ id }));
}
save(place: Place, name: string) {
const update = { id: place.id, changes: { name } };
this.store.dispatch(PlacesPageActions.updatePlace({ update }));
}
}
We updated our form components to use the new actions and state refactored, lets move , let’s check our effects to ensure they work correctly with NgRx Entities
Refactoring Effects
Finally, I will make the effects work with NgRx Entities, we only need to update the PlacesPageActions.updatePlace
pass the correct Update<Place>
object in the updatePlaceEffect$
effect.
export const updatePlaceEffect$ = createEffect(
(actions$ = inject(Actions), placesService = inject(PlacesService)) => {
return actions$.pipe(
ofType(PlacesPageActions.updatePlace),
concatMap(({ update }) =>
placesService.update(update.changes).pipe(
map((updatedPlace) =>
PlacesApiActions.updateSuccess({ place: updatedPlace })
),
catchError((error) =>
of(PlacesApiActions.updateFailure({ message: error })),
),
),
),
);
},
{ functional: true },
);
Done! I did our app is working with NgRx Entities and the migration was so easy !, the documentation of ngrx entity is very helpfull and
Conclusion
After moving my code to NgRx Entities, I felt it helped reduce complexity and boilerplate when working with collections. NgRx Entities simplify working with collections and interactions with its large number of methods for most scenarios, eliminating much of the boilerplate code needed for CRUD operations.
I hope this article motivates you to use ngrx-entities when you need to work with collections in ngrx.
Subscribe to my newsletter
Read articles from Dany Paredes directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Dany Paredes
Dany Paredes
I'm passionate about front-end development, specializing in building UI libraries and working with technologies like Angular, NgRx, Accessibility, and micro-frontends. In my free time, I enjoy writing content for the Google Dev Library, This Is Angular Community, Kendo UI, and sharing insights here.