Sub topic 10
Managing collections with withEntities
This chapter assumes you can already build a signal store with withState, withMethods and patchState, and that you know Angular signals. Here you will store a list of items by id instead of in a plain array.
Why not a plain array
A todos: Todo[] array works for small lists. Finding, updating or removing one item means scanning the array and rebuilding it with map or filter. That code is repetitive, and you will write it for every collection in your app.
withEntities removes that work. It adds a normalized collection to the store, with ids kept in order and the items kept in a lookup object. It also provides updater functions that you pass to patchState.
What withEntities adds
Calling withEntities<Product>() adds three members to the store:
| Member | Kind | Meaning |
|---|---|---|
| `ids` | state signal | Array of entity ids, in order |
| `entityMap` | state signal | Object that maps each id to its entity |
| `entities` | computed signal | Array of entities, built from `ids` and `entityMap` |
Only ids and entityMap are state. entities is derived from them.
A first entity store
import { patchState, signalStore, withMethods } from '@ngrx/signals';
import { addEntity, removeEntity, updateEntity, withEntities } from '@ngrx/signals/entities';
type Product = { id: number; name: string };
export const ProductsStore = signalStore(
{ providedIn: 'root' },
withEntities<Product>(),
withMethods((store) => ({
add(product: Product): void {
patchState(store, addEntity(product));
},
rename(id: number, name: string): void {
patchState(store, updateEntity({ id, changes: { name } }));
},
remove(id: number): void {
patchState(store, removeEntity(id));
},
})),
);Each updater returns a partial state change, and patchState applies it immutably. updateEntity merges changes into the existing entity, so you pass only the fields that change.
In a component, use store.entities() to render a list. Use store.entityMap()[id] for a direct lookup without scanning.
Choosing an updater
The updaters differ in what they do when the id already exists or is missing.
addEntityandaddEntitiesadd new items. They ignore an item whose id already exists.setEntityandsetEntitiesadd or fully replace items by id.upsertEntityadds an item, or merges it into an existing one.updateEntityandupdateEntitiesmerge changes into existing items. They do nothing if the id is missing.removeEntity,removeEntitiesandremoveAllEntitiesdelete items.
A common choice is setEntities after a server response, because it replaces the whole collection with fresh data.
Custom ids
By default, withEntities reads the id property of each entity. If your type uses a different key, supply a selectId function through an entity config.
import { patchState, signalStore, type, withMethods } from '@ngrx/signals';
import { entityConfig, setEntities, withEntities } from '@ngrx/signals/entities';
type Book = { isbn: string; title: string };
const bookConfig = entityConfig({
entity: type<Book>(),
selectId: (book) => book.isbn,
});
export const BooksStore = signalStore(
withEntities(bookConfig),
withMethods((store) => ({
load(books: Book[]): void {
patchState(store, setEntities(books, bookConfig));
},
})),
);Pass the same config to each updater. Otherwise the updater falls back to the id property and uses the wrong key.
Combining entities with other state
withEntities works next to withState. A typical store has entities plus fields such as filter or loading. You can derive a filtered list with withComputed that reads entities(), just as the earlier chapter derived visibleTodos from todos().
Common errors
- Mutating an entity from
entityMap()directly. These objects are state, so change them only through updaters. - Using
addEntityto refresh data. It ignores existing ids, so usesetEntityorupsertEntity. - Passing
changesthat contain the id. Updaters do not change an entity's id this way. Remove and add the entity instead.
Exercise
A server returns an updated list of products, and some already exist in the store. Which updater should the load method use to make the store match the response exactly, and why not addEntities?
Show answer
Use setEntities. It replaces the whole collection with the given items. addEntities ignores items whose ids already exist, so stale entities would remain and the store would not match the response.