Sub topic 10
Managing collections with withEntities
This chapter assumes you can already build a store with withState, withComputed and withMethods, and that you update state with patchState. It also assumes you know what an array of objects with an id field looks like. You will learn how withEntities stores a collection, which updaters change it, and where its defaults can surprise you.
Why a feature for collections
A list of items is the most common shape in application state. Storing it as a plain array works at first. Then every update needs a map or filter that scans the whole array to find one item. Looking up an item by id is a linear search. Each store ends up with its own slightly different add, update and remove code.
withEntities solves this by storing the collection in a normalized form: a list of ids plus an object that maps each id to its item. It also provides a set of tested updater functions that you pass to patchState.
What withEntities adds to a store
Call withEntities<T>() with your item type. It adds two state slices and one computed signal.
| Member | Kind | Content |
|---|---|---|
| `ids` | state signal | Array of ids, in insertion 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 real state. The entities array is derived from them, so it is recomputed when they change.
import { patchState, signalStore, withMethods } from '@ngrx/signals';
import { addEntity, removeEntity, updateEntity, withEntities } from '@ngrx/signals/entities';
type Product = { id: number; name: string; price: number };
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));
},
})),
);In a component, store.entities() returns the array to render. store.entityMap()[id] returns one item without scanning.
The entity updaters
The updaters are plain functions that return a partial state change. They do nothing until you pass them to patchState. They are also immutable: each one produces new ids and entityMap objects instead of changing the old ones.
| Updater | Behavior |
|---|---|
| `addEntity` / `addEntities` | Appends entities. An entity whose id already exists is ignored. |
| `prependEntity` / `prependEntities` | Adds entities at the start of `ids`. Available in recent versions. |
| `setEntity` / `setEntities` | Adds an entity, or replaces the existing one with the same id. |
| `setAllEntities` | Replaces the whole collection. |
| `updateEntity` / `updateEntities` | Applies a partial change to existing entities. Missing ids are ignored. |
| `upsertEntity` / `upsertEntities` | Adds the entity if it is new, or merges it into the existing one. |
| `removeEntity` / `removeEntities` | Removes by id, or by predicate for `removeEntities`. |
| `removeAllEntities` | Empties the collection. |
Check the version of @ngrx/signals you installed if a name above is missing. The set has grown across releases.
Add versus set versus upsert
These three are easy to confuse, and the differences matter when you refresh data from a server.
addEntitynever overwrites. If id1already exists, the call changes nothing. That is useful for "create" actions, and it hides bugs when you expected a refresh.setEntityreplaces the whole entity. Any property missing from the new object is gone.upsertEntitymerges. Properties you pass overwrite the old ones, and properties you leave out stay. The merge is shallow, so a nested object is replaced as a whole.
patchState(store, addEntity({ id: 1, name: 'Desk', price: 200 }));
patchState(store, addEntity({ id: 1, name: 'Chair', price: 90 }));
// store.entityMap()[1].name is still 'Desk'
patchState(store, upsertEntity({ id: 1, name: 'Standing desk', price: 200 }));
// name is now 'Standing desk'Updating several entities
updateEntity takes one id and a changes object. updateEntities takes either a list of ids or a predicate, plus the changes. The changes value can also be a function that receives the current entity and returns a partial one, which you need when the new value depends on the old one.
import { patchState, signalStore, withMethods } from '@ngrx/signals';
import {
removeEntities,
setAllEntities,
updateEntities,
withEntities,
} from '@ngrx/signals/entities';
type Product = { id: number; name: string; price: number };
export const PricingStore = signalStore(
{ providedIn: 'root' },
withEntities<Product>(),
withMethods((store) => ({
load(products: Product[]): void {
patchState(store, setAllEntities(products));
},
applyDiscount(percent: number): void {
patchState(
store,
updateEntities({
predicate: (p) => p.price > 100,
changes: (p) => ({ price: Math.round(p.price * (1 - percent / 100)) }),
}),
);
},
removeCheap(): void {
patchState(store, removeEntities((p) => p.price < 10));
},
})),
);Combining several updaters in one call
patchState accepts any number of updaters and applies them in order, producing one state change. Use this when two changes belong together, for example clearing a collection and storing a new one. Components then see one consistent update instead of an intermediate state.
patchState(store, removeAllEntities(), addEntities(freshProducts), { loading: false });The last argument is an ordinary partial state object. Entity updaters and plain objects mix freely.
Custom ids with selectId
By default the id is the entity's id property. If your items use another key, such as sku, pass selectId to each updater. Defining an entity config once keeps this in one place.
import { patchState, signalStore, withMethods } from '@ngrx/signals';
import {
entityConfig,
setAllEntities,
withEntities,
} from '@ngrx/signals/entities';
import { type } from '@ngrx/signals';
type Item = { sku: string; label: string };
const itemConfig = entityConfig({
entity: type<Item>(),
selectId: (item) => item.sku,
});
export const ItemsStore = signalStore(
{ providedIn: 'root' },
withEntities(itemConfig),
withMethods((store) => ({
load(items: Item[]): void {
patchState(store, setAllEntities(items, itemConfig));
},
})),
);Pass the same config to the updaters. If you forget it, the updater falls back to the id property, and you get undefined ids at runtime. TypeScript can flag this for entity types with no id field, but not when an id field exists and is the wrong key.
Named collections
A store can hold more than one collection. Give each a name with the collection option. The names of the state and computed members are then prefixed.
import { patchState, signalStore, type, withMethods } from '@ngrx/signals';
import { addEntity, entityConfig, withEntities } from '@ngrx/signals/entities';
type User = { id: number; name: string };
type Group = { id: number; title: string };
const userConfig = entityConfig({ entity: type<User>(), collection: 'user' });
const groupConfig = entityConfig({ entity: type<Group>(), collection: 'group' });
export const DirectoryStore = signalStore(
{ providedIn: 'root' },
withEntities(userConfig),
withEntities(groupConfig),
withMethods((store) => ({
addUser(user: User): void {
patchState(store, addEntity(user, userConfig));
},
addGroup(group: Group): void {
patchState(store, addEntity(group, groupConfig));
},
})),
);This store exposes userIds, userEntityMap, userEntities, groupIds, groupEntityMap and groupEntities. Every updater call must receive the matching config. Passing userConfig to a group update would write into the wrong collection.
Deriving selected and filtered data
The entities signal is the input for further computed values. Selection is a typical case. Store only the selected id as state, and derive the selected entity.
import { computed } from '@angular/core';
import { patchState, signalStore, withComputed, withMethods, withState } from '@ngrx/signals';
import { setAllEntities, withEntities } from '@ngrx/signals/entities';
type Product = { id: number; name: string; price: number };
export const CatalogStore = signalStore(
{ providedIn: 'root' },
withEntities<Product>(),
withState({ selectedId: null as number | null, maxPrice: 500 }),
withComputed(({ entities, entityMap, selectedId, maxPrice }) => ({
selected: computed(() => {
const id = selectedId();
return id === null ? undefined : entityMap()[id];
}),
affordable: computed(() => entities().filter((p) => p.price <= maxPrice())),
})),
withMethods((store) => ({
load(products: Product[]): void {
patchState(store, setAllEntities(products));
},
select(id: number | null): void {
patchState(store, { selectedId: id });
},
})),
);Storing the id, not a copy of the entity, avoids stale data. When the product is updated, selected reflects the change because it reads from entityMap. If the selected entity is removed, selected becomes undefined, but selectedId still holds the old id. Clear it in the same patchState call as the removal if that matters for your screen.
Loading entities from a server
Combine the entity updaters with the request pattern from the rxMethod chapter. On success, call setAllEntities to replace the collection with the server's copy. Use upsertEntities instead when a response contains only part of the collection, such as one page, and you want to keep items loaded earlier.
Common errors
- Mutating entities in place. Writing
store.entityMap()[1].name = 'x'changes the object without notifying signals. UseupdateEntity. - Expecting
addEntityto refresh. It ignores existing ids. UsesetEntityorupsertEntity. - Using
setEntityfor partial data. It drops properties you left out. UseupdateEntityorupsertEntity. - Forgetting the config. With
selectIdorcollection, every updater needs the same config. - Relying on
entityMapordering. Order lives inids. Readentities()when order matters. - Updating a missing id.
updateEntitydoes nothing for an unknown id and reports no error. UseupsertEntityif the item may not exist yet.
When not to use withEntities
Use it for collections of items identified by a key that you add, change and remove individually. For a small, read-only list that you only replace as a whole, a plain array in withState is simpler. For a single object, there is no need for a collection at all.
Exercise
A store holds products with withEntities<Product>(). A server refresh returns { id: 3, price: 15 } for a product that is already stored as { id: 3, name: 'Lamp', price: 20 }. Which updater leaves name as 'Lamp' while setting price to 15, and what do addEntity and setEntity do instead?
Show answer
upsertEntity (or updateEntity, since the id already exists) merges the new properties into the stored entity, so the result is { id: 3, name: 'Lamp', price: 15 }. addEntity ignores the call because id 3 already exists, so the price stays 20. setEntity replaces the whole entity, so the result is { id: 3, price: 15 } and name is lost.
Exercise
A store defines two named collections with userConfig (collection 'user') and groupConfig (collection 'group'). A method calls patchState(store, addEntity(group)) without a config. What happens, and how do you fix it?
Show answer
The updater has no collection name, so it writes to the unprefixed ids and entityMap instead of groupIds and groupEntityMap. groupEntities() stays empty and the item sits in stray state. Fix it by passing the config: addEntity(group, groupConfig).