Home >Web Front-end >JS Tutorial >Simplify Your Angular Code with NgRx Entities

Simplify Your Angular Code with NgRx Entities

DDD
DDDOriginal
2024-10-29 06:37:30482browse

Simplify Your Angular Code with 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.

interface EntityState<V> {
  ids: string[] | number[];
  entities: { [id: string | id: number]: V };
}

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:

export const adapter: EntityAdapter<Place> = createEntityAdapter<Place>();

?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.

git clone https://github.com/danywalls/start-with-ngrx.git
git checkout crud-ngrx
cd start-with-ngrx

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.

npm i
ng add @ngrx/entity

Next, initialize the entity adapter for our Place entity using createEntityAdapter:

interface EntityState<V> {
  ids: string[] | number[];
  entities: { [id: string | id: number]: V };
}

Finally, replace the manual initialState with the one provided by the adapter using getInitialState:

export const adapter: EntityAdapter<Place> = createEntityAdapter<Place>();

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.

In places.actions.ts, we update the Update Place action to use Update, which allows us to modify only part of an entity:

git clone https://github.com/danywalls/start-with-ngrx.git
git checkout crud-ngrx
cd start-with-ngrx

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:

npm i
ng add @ngrx/entity

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:

export type PlacesState = {
  placeSelected: Place | undefined;
  loading: boolean;
  error: string | undefined;
} & EntityState<Place>;

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 type when saving changes:

interface EntityState<V> {
  ids: string[] | number[];
  entities: { [id: string | id: number]: V };
}

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 object in the updatePlaceEffect$ effect.

export const adapter: EntityAdapter<Place> = createEntityAdapter<Place>();

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.

  • source code: https://github.com/danywalls/start-with-ngrx/tree/ngrx-entities

Photo by Yonko Kilasi on Unsplash

The above is the detailed content of Simplify Your Angular Code with NgRx Entities. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn