@rx-mind/component-store-helpers
v14.0.0
Published
Component Store Helpers for Better Developer Experience
Downloads
5
Maintainers
Readme
@rx-mind/component-store-helpers
Component Store Helpers for Better Developer Experience
Contents
Installation
- NPM:
npm i @rx-mind/component-store-helpers
- Yarn:
yarn add @rx-mind/component-store-helpers
Note:
@rx-mind/component-store-helpers
has@ngrx/component-store
as a peer dependency.
API
getComponentStateSelectors
The getComponentStateSelectors
function returns an object that contains state selectors for the passed ComponentStore
.
The name of each generated selector will be equal to the name of the state property with the $
suffix.
Usage Notes
import { ComponentStore } from '@ngrx/component-store';
import { getComponentStateSelectors } from '@rx-mind/component-store-helpers';
interface UsersState {
users: User[];
isLoading: boolean;
selectedUserId: string | null;
}
const initialState: UsersState = {
users: [],
isLoading: false,
selectedUserId: null,
};
@Injectable()
export class UsersStore extends ComponentStore<UsersState> {
private readonly selectors = getComponentStateSelectors(this);
readonly vm$ = this.select(
this.selectors.users$,
this.selectors.isLoading$,
this.selectors.selectedUserId$,
(users, isLoading, selectedId) => ({
users,
isLoading,
selectedUser: users.find((user) => user.id === selectedId) ?? null,
})
);
constructor() {
super(initialState);
}
}
Restrictions
The getComponentStateSelectors
function cannot be used for ComponentStore
whose state contains optional properties.
This can be solved by using | null
or | undefined
for nullish state properties.
Before:
interface UsersState {
users: User[];
selectedUserId?: string;
}
const initialState: UsersState = {
users: [],
};
After:
interface UsersState {
users: User[];
selectedUserId: string | null;
// or selectedUserId: string | undefined;
}
const initialState: UsersState = {
users: [],
selectedUserId: null,
// or selectedUserId: undefined,
};
Limitations
The getComponentStateSelectors
function cannot be used for ComponentStore
whose state is initialized lazily.
@Injectable()
export class UsersStore extends ComponentStore<UsersState> {
// this will throw an error because the state is not initialized on `UsersStore` initialization
readonly selectors = getComponentStateSelectors(this);
constructor() {
// initial state is not passed to the parent constructor
super();
}
}