Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions modules/signals/spec/state-source.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
effect,
EnvironmentInjector,
Injectable,
linkedSignal,
signal,
} from '@angular/core';
import { TestBed } from '@angular/core/testing';
Expand Down Expand Up @@ -61,6 +62,19 @@ describe('StateSource', () => {
});

describe('patchState', () => {
it('does not read unrelated state slices for partial state objects', () => {
const name = signal('');
const inaccessible = linkedSignal(() => {
throw new Error('Failed to read state slice');
});
const stateSource = {
[STATE_SOURCE]: { name, inaccessible },
};

expect(() => patchState(stateSource, { name: 'John' })).not.toThrow();
expect(name()).toBe('John');
});

[
{
name: 'with signalState',
Expand Down
14 changes: 11 additions & 3 deletions modules/signals/src/state-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,18 @@ export function patchState<State extends object>(
Partial<NoInfer<State>> | PartialStateUpdater<NoInfer<State>>
>
): void {
const currentState = untracked(() => getState(stateSource));
const requiresCurrentState = updaters.some(
(updater) => typeof updater === 'function'
);
const currentState = requiresCurrentState
? untracked(() => getState(stateSource))
: undefined;
const newState = updaters.reduce(
(nextState: State, updater) => ({
...nextState,
...(typeof updater === 'function' ? updater(nextState) : updater),
}),
currentState
currentState ?? ({} as State)
);

const signals = stateSource[STATE_SOURCE];
Expand All @@ -97,7 +102,10 @@ export function patchState<State extends object>(
for (const key of Reflect.ownKeys(newState)) {
if (stateKeys.includes(key)) {
const signalKey = key as keyof State;
if (currentState[signalKey] !== newState[signalKey]) {
const currentValue = currentState
? currentState[signalKey]
: untracked(() => signals[signalKey]());
if (currentValue !== newState[signalKey]) {
signals[signalKey].set(newState[signalKey]);
}
} else if (typeof ngDevMode !== 'undefined' && ngDevMode) {
Expand Down