16 - Entity State Adapter
In this section we add entity adapter
1. npm install entity from NgRx
In the past you had to install the @ngrx/entity package separately. Now, you might have noticed in step 13 when we generated our store with the @nrwl/angular:ngrx schematic, it was added automatically. Here is a brief overview of the Entity package and why we use it.
The store is like an in-memory database, and the Entity class gives a unique identifier to each object similar to a primary key. In this way objects can then be flattened out and linked together using the entity unique identifiers, just like in a database. This makes it simpler to combine the multiple entities and 'join' them via a selector query.
The Entity State format consists of the objects in a map called "entities", and store the order of the objects in an array of ids.
The Adapter is a utility class that provides a series of functions designed to make it really simple to manipulate the entity state, such as changing the order.
You can find out more by reading this Angular University piece on the subject.
2. Use entity adapter in reducer
Extend ProductState with EntityState. By default it will make an entities and ids dictionary. You Add to this any state properties you desire.
Create an adapter and use it's getInitialState method to make the initial state
3. Update the default reducer logic
Adapter Collection Methods
The entity adapter also provides methods for operations against an entity. These methods can change one to many records at a time. Each method returns the newly modified state if changes were made and the same state if no changes were made.
addOne
: Add one entity to the collectionaddMany
: Add multiple entities to the collectionsetAll
: Replace current collection with provided collectionsetOne
: Add or Replace one entity in the collection.setMany
: Add or Replace multiple entities in the collectionremoveOne
: Remove one entity from the collectionremoveMany
: Remove multiple entities from the collectionremoveAll
: Clear entity collectionupdateOne
: Update one entity in the collectionupdateMany
: Update multiple entities in the collectionupsertOne
: Add or Update one entity in the collectionupsertMany
: Add or Update multiple entities in the collectionmapOne
: Update one entity in the collection by defining a map functionmap
: Update multiple entities in the collection by defining a map function, similar to Array.map
https://ngrx.io/guide/entity/adapter
4. Add selector methods to bottom of reducer
5. Add default selectors to use entity adapter
6. Examine State tree in Devtools
At this point, if you run the app however, you might get an error like this:
The app is not going to run now without updating the products component. This will be fixed in the next step.
Last updated