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

Simplify Your Angular Code with NgRx Entities

Oct 29, 2024 am 06:37 AM

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 };
}
Copy after login
Copy after login
Copy after login
Copy after login

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 };
}
Copy after login
Copy after login
Copy after login
Copy after login

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>();
Copy after login
Copy after login
Copy after login

?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
Copy after login
Copy after login

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
Copy after login
Copy after login

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

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

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

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

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
Copy after login
Copy after login

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
Copy after login
Copy after login

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>;
Copy after login

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 };
}
Copy after login
Copy after login
Copy after login
Copy after login

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>();
Copy after login
Copy after login
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles