NgRx · Entity · State Management
NgRx Entity is a helper library that makes it easier to manage large collections of entities (like users, products, or posts) in the NgRx store. It provides adapters and utility methods for common CRUD operations so that you write less boilerplate and keep your state normalized, predictable, and easy to query.
User record).selectAll) to read entities from the store.To use NgRx Entity, you typically:
User).EntityState<User> to describe the feature state.EntityAdapter<User> using createEntityAdapter.adapter.getInitialState().addOne, removeOne, and setAll inside a reducer.
// Use NgRx Entity to manage a collection of User records in the store
export interface User {
id: string;
name: string;
email: string;
}
import { createEntityAdapter, EntityState } from '@ngrx/entity';
import { createReducer, on } from '@ngrx/store';
import { addUser, removeUser, loadUsersSuccess } from './user.actions';
export interface UserState extends EntityState<User> {}
export const adapter = createEntityAdapter<User>();
const initialState: UserState = adapter.getInitialState();
export const userReducer = createReducer(
initialState,
on(addUser, (state, { user }) => adapter.addOne(user, state)),
on(removeUser, (state, { id }) => adapter.removeOne(id, state)),
on(loadUsersSuccess, (state, { users }) => adapter.setAll(users, state))
);
export const { selectAll, selectEntities } = adapter.getSelectors();
addUser is dispatched, the reducer calls adapter.addOne(user, state), which adds the new user to the normalized collection and keeps IDs in sync.removeUser is dispatched, adapter.removeOne(id, state) removes the user from both the entity dictionary and its IDs list.loadUsersSuccess uses adapter.setAll(users, state) to replace the current collection with the loaded list.selectAll to get an array of all users, or selectEntities to get a dictionary keyed by ID.NgRx Entity for large collections to avoid manual CRUD logic.*Failure actions in effects.actions, reducers, effects, selectors, and models.User feature using NgRx Entity with add, remove, and load actions.selectAll).selectEntities or a custom selector).updateOne, upsertOne, and upsertMany.UserState with extra UI properties (like loading or error) using adapter.getInitialState({ ...extraProps }).