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 }; } </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 }; } </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>(); </place></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 }; } </v>
Finally, replace the manual initialState with the one provided by the adapter using getInitialState:
export const adapter: EntityAdapter<place> = createEntityAdapter<place>(); </place></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
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>; </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
interface EntityState<v> { ids: string[] | number[]; entities: { [id: string | id: number]: V }; } </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
export const adapter: EntityAdapter<place> = createEntityAdapter<place>(); </place></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!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
