Sub topic 12
Sharing logic with signalStoreFeature
This chapter assumes you can build a store with withState, withComputed and withMethods, and that you update state with patchState. If several stores in your app repeat the same slice of state, such as a loading flag, you can package that slice once with signalStoreFeature.
The problem: repeated store code
Suppose an orders store, a users store and a products store each track whether a request is idle, pending, fulfilled or failed. Without a shared feature, each store declares the same state and the same computed signals. A fix in one copy then has to be repeated in the others.
signalStoreFeature takes the same with... building blocks as signalStore and returns them as one reusable unit. You then add that unit to any store, the same way you add withState.
Building a feature
A feature is usually a plain function that returns signalStoreFeature(...). The function form lets you add parameters later.
import { computed } from '@angular/core';
import {
patchState,
signalStore,
signalStoreFeature,
withComputed,
withMethods,
withState,
} from '@ngrx/signals';
export type RequestStatus = 'idle' | 'pending' | 'fulfilled' | { error: string };
export function withRequestStatus() {
return signalStoreFeature(
withState<{ requestStatus: RequestStatus }>({ requestStatus: 'idle' }),
withComputed(({ requestStatus }) => ({
isPending: computed(() => requestStatus() === 'pending'),
error: computed(() => {
const status = requestStatus();
return typeof status === 'object' ? status.error : null;
}),
})),
);
}
export const setPending = () => ({ requestStatus: 'pending' as const });
export const setFulfilled = () => ({ requestStatus: 'fulfilled' as const });
export const setError = (error: string) => ({ requestStatus: { error } });
export const OrdersStore = signalStore(
withRequestStatus(),
withMethods((store) => ({
start(): void {
patchState(store, setPending());
},
finish(): void {
patchState(store, setFulfilled());
},
fail(message: string): void {
patchState(store, setError(message));
},
})),
);OrdersStore now exposes requestStatus, isPending and error without declaring them itself. The three small functions setPending, setFulfilled and setError are state updaters. Each returns a partial state object, so any store that uses the feature can pass them to patchState and change the status in the same way.
Order matters
A store applies its features from top to bottom. Each feature can use the members added before it, but not the ones added after it. In OrdersStore, withMethods comes after withRequestStatus(), so the methods can call patchState on requestStatus. If you reversed the order, TypeScript would report that requestStatus does not exist.
Features that depend on the store
Some features need state that another feature provides. Declare that requirement as an input with type<...>(). The compiler then rejects any store that does not already contain the required members.
import { patchState, signalStoreFeature, type, withMethods } from '@ngrx/signals';
import type { RequestStatus } from './request-status';
export function withStatusReset() {
return signalStoreFeature(
{ state: type<{ requestStatus: RequestStatus }>() },
withMethods((store) => ({
resetStatus(): void {
patchState(store, { requestStatus: 'idle' });
},
})),
);
}You can place withStatusReset() after withRequestStatus() in a store. If you place it before, or in a store without requestStatus, the code does not compile. Inputs can also require props and methods, not only state.
Common mistakes
- Putting a feature after the code that uses its members. Move it earlier in the list.
- Declaring a state key that another feature already uses. Names in one store must be unique, so prefix keys in generic features, for example
requestStatusinstead ofstatus. - Sharing one mutable object between stores. Features should create fresh initial state each time the function runs, and updates should return new objects.
- Forgetting that each store instance gets its own copy of the feature's state. A feature shares code, not values.
Exercise
You write withPagination(), which adds a pageSize state value and a setPageSize method. You add it to a store after withMethods, and a method defined in that withMethods block calls store.setPageSize. The code does not compile. What is wrong, and how do you fix it?
Show answer
Features are applied from top to bottom, so the earlier withMethods block cannot see setPageSize, which is added later. Move withPagination() above the withMethods block that uses it.