Skip to content

Commit 79b0708

Browse files
authored
feat(signals): add getState function (#4118)
1 parent 1b322d5 commit 79b0708

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import { TestBed } from '@angular/core/testing';
2+
import {
3+
getState,
4+
patchState,
5+
signalState,
6+
signalStore,
7+
withState,
8+
} from '../src';
9+
import { effect } from '@angular/core';
10+
11+
describe('getState', () => {
12+
const initialState = {
13+
user: {
14+
firstName: 'John',
15+
lastName: 'Smith',
16+
},
17+
foo: 'bar',
18+
numbers: [1, 2, 3],
19+
ngrx: 'signals',
20+
};
21+
22+
describe('with signalStore', () => {
23+
it('returns the state object', () => {
24+
const Store = signalStore(withState(initialState));
25+
const store = new Store();
26+
27+
expect(getState(store)).toEqual(initialState);
28+
});
29+
30+
it('executes in the reactive context', () => {
31+
const Store = signalStore(withState(initialState));
32+
const store = new Store();
33+
34+
let executionCount = 0;
35+
36+
TestBed.runInInjectionContext(() => {
37+
effect(() => {
38+
getState(store);
39+
executionCount++;
40+
});
41+
});
42+
43+
TestBed.flushEffects();
44+
expect(executionCount).toBe(1);
45+
46+
patchState(store, { foo: 'baz' });
47+
48+
TestBed.flushEffects();
49+
expect(executionCount).toBe(2);
50+
expect(getState(store)).toEqual({ ...initialState, foo: 'baz' });
51+
});
52+
});
53+
});

modules/signals/src/get-state.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import { STATE_SIGNAL, SignalStateMeta } from './signal-state';
2+
3+
export function getState<State extends Record<string, unknown>>(
4+
signalState: SignalStateMeta<State>
5+
): State {
6+
return signalState[STATE_SIGNAL]();
7+
}

modules/signals/src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
export { getState } from './get-state';
12
export { PartialStateUpdater, patchState } from './patch-state';
23
export { signalState } from './signal-state';
34
export { signalStore } from './signal-store';

0 commit comments

Comments
 (0)