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.
Before diving into code, let's first understand what NgRx Entities are and why you should consider using them.
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.
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.
NgRx Entities provides tools such as EntityState, EntityAdapter, and predefined selectors to streamline working with collections.
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{ ids: string[] | number[]; entities: { [id: string | id: number]: V }; }
Read more about Entity State
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= createEntityAdapter ();
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
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.
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!
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
export type PlacesState = { placeSelected: Place | undefined; loading: boolean; error: string | undefined; } & EntityState;
Next, initialize the entity adapter for our Place entity using createEntityAdapter:
const adapter: EntityAdapter= createEntityAdapter ();
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.
In the previous articles, I manually handled updates and modifications to entities. Now, we will use NgRx Entities to handle partial updates using Update
In places.actions.ts, we update the Update Place action to use Update
import { Update } from '@ngrx/entity'; export const PlacesPageActions = createActionGroup({ source: 'Places', events: { 'Load Places': emptyProps(), 'Add Place': props(), 'Update Place': props }>(), // Use Update'Delete Place': props(), 'Select Place': props(), '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.
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.
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('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.
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
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
Finally, I will make the effects work with NgRx Entities, we only need to update the PlacesPageActions.updatePlace pass the correct Update
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
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.
Photo by Yonko Kilasi on Unsplash
Отказ от ответственности: Все предоставленные ресурсы частично взяты из Интернета. В случае нарушения ваших авторских прав или других прав и интересов, пожалуйста, объясните подробные причины и предоставьте доказательства авторских прав или прав и интересов, а затем отправьте их по электронной почте: [email protected]. Мы сделаем это за вас как можно скорее.
Copyright© 2022 湘ICP备2022001581号-3