Sub topic 3
Defining state with withState
This chapter assumes you know Angular components and dependency injection, Angular signals (signal, computed), and TypeScript object types. You should also have seen signalStore from the previous chapter. Here you will define the state a store holds and see what the store exposes from it.
What withState does
withState is a store feature that gives a store its initial state. You pass it an object. The store turns each top-level property of that object into a read-only signal with the same name.
import { signalStore, withState } from '@ngrx/signals';
type Filter = 'all' | 'open' | 'done';
type Todo = { id: number; title: string; done: boolean };
type TodosState = { todos: Todo[]; filter: Filter };
const initialState: TodosState = { todos: [], filter: 'all' };
export const TodosStore = signalStore(
{ providedIn: 'root' },
withState(initialState),
);An instance of TodosStore now has two members, todos and filter. Each is a signal, so you read it by calling it: store.todos() and store.filter().
Typing the state
Declare the state type yourself and annotate the initial value with it, as in the example above. Without the annotation, TypeScript infers filter: string from 'all' and todos: never[] from []. Both inferred types are too loose to use.
You can also give the type as a generic argument:
withState<TodosState>({ todos: [], filter: 'all' })Both forms work. The annotated constant is easier to reuse in tests.
Rules for the state shape
- The state must be a plain object. Arrays, primitives and class instances cannot be the root of the state.
- Prefer
nulloverundefinedfor "no value yet", for exampleerror: string | null. The property then stays present and its type stays explicit. - Keep the state serializable. Use
string,number,boolean, arrays and plain objects. AvoidMap,Setand class instances, because they are awkward to update immutably and to inspect. - Store only the facts. Values you can compute from other state, such as a count of open todos, belong in
withComputed, which a later chapter covers.
Using a factory function
withState also accepts a function that returns the state. The store calls it once for each store instance.
import { signalStore, withState } from '@ngrx/signals';
type SessionState = { sessionId: string; items: string[] };
export const SessionStore = signalStore(
withState(() => ({
sessionId: crypto.randomUUID(),
items: [] as string[],
})),
);Use the factory form when the initial value must be computed per instance. This matters for component-level stores, where each component gets its own store.
Several withState calls
You can call withState more than once in the same store. The features run in order, and each adds its own signals.
import { signalStore, withState } from '@ngrx/signals';
export const PageStore = signalStore(
withState({ title: '' }),
withState({ loading: false }),
);Property names must be unique across the whole store. In current versions, a clash between a state property and another member is reported in the console in development mode.
Common errors
- Forgetting to call the signal. In a template,
{{ store.filter }}shows the signal function, not its value. Write{{ store.filter() }}. - Assigning to a state signal.
store.filter.set('open')does not compile, because the state signals are read-only outside the store. Changing state is the job ofpatchState, covered in the next chapter. - Widened literal types. Leaving out the type annotation turns
'all'intostring, so laterpatchStatecalls accept any string. - Optional properties. A property declared as
error?: stringmay be missing from the object. Declareerror: string | nulland set it tonullinitially.
Exercise
A store is defined with withState({ user: null as string | null, count: 0 }). What type does store.count have, how do you read its current value in a template, and why does store.count.set(1) fail?
Show answer
store.count is a read-only signal of number (Signal<number>). In a template you read it with store.count(). set fails because state signals are read-only outside the store, so you change state with patchState instead.