This is the third article of the series about @ngrx/entity.
- Managing Your Collections With EntityAdapter
- Multiple Entity Collections in the Same Feature State
- Using EntityAdapter With ComponentStore
Headsup
If you have followed the series, you should be familiar with the
EntityState
interface. It describes how the EntityAdapter
expects our collection to be stored. In the previous articles, we elaborated in detail on how to handle single and multiple collections.For this example, we simply make
EntityState
the state of our component and extend it with a couple of common properties. But everything shown before, when we need to handle multiple entity types, applies here as well!Basic Setup
We start out by simply defining our component state interface, which will contain a single collection and some properties. We do this by extending
EntityState
:
interface PersonComponentState extends EntityState {
loading: boolean;
error?: string;
}
Creating the
EntityAdapter
and the initial state can be done as before, and the ComponentStore goes along with it:
const personAdapter = createEntityAdapter();
const initialState = personAdapter.getInitialState({ loading: true });
@Injectable()
class PersonComponentStore extends ComponentStore {
constructor() {
super(initialState);
}
}
Selector and Updater Bliss
Using the
EntityAdapter
, we can now easily manage our collection as we have seen before in our reducer functions, which will now simply become updaters:
class PersonComponentStore extends ComponentStore {
// ...
readonly addPerson = this.updater((state, person: Person) => {
return personAdapter.addOne(person, state);
});
readonly updatePerson = this.updater((state, update: Update) => {
return personAdapter.updateOne(update, state);
});
// ...
}
For selectors, we need to extract them from the
EntityAdapter
first:
// ...
const { selectAll } = personAdapter.getSelectors();
class PersonComponentStore extends ComponentStore {
readonly persons$ = this.select(state => selectAll(state));
// ...
}
Conclusion
In this series, I have shown, that using the
@ngrx/entity
package is quite simple and often beneficial. The way this abstraction is implemented allows us to make use of the EntityAdapter
in various ways.As this is the last part of this series, it is kept very brief. Please refer to the other parts for a detailed dive into how
EntityAdapter
works!I hope I could inspire you to make use of the entity package!