From 6780d964d17b968d1af4717d7c94a2d3a4fec8d6 Mon Sep 17 00:00:00 2001 From: Andreas Dorner Date: Thu, 2 Jul 2026 19:43:36 +0200 Subject: [PATCH] feat(connect): enhance reducer behavior for falsy values in signal updates --- libs/ngxtension/connect/src/connect.spec.ts | 36 +++++++++++++++++++++ libs/ngxtension/connect/src/connect.ts | 4 +-- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/libs/ngxtension/connect/src/connect.spec.ts b/libs/ngxtension/connect/src/connect.spec.ts index e6666d9f6..19967cf73 100644 --- a/libs/ngxtension/connect/src/connect.spec.ts +++ b/libs/ngxtension/connect/src/connect.spec.ts @@ -371,6 +371,42 @@ describe(connect.name, () => { }); }); + describe('reducer returning a falsy value', () => { + it('should use the reducer result instead of the raw emission when it is a falsy primitive', () => { + const isActive = signal(true); + + TestBed.runInInjectionContext(() => { + connect(isActive, of('toggle'), () => false); + }); + + expect(isActive()).toBe(false); + }); + + it('should use a reducer result of 0 instead of falling back to the raw emission', () => { + const count = signal(5); + + TestBed.runInInjectionContext(() => { + // reducer computes a delta which legitimately evaluates to 0 + connect(count, of(5), (prev, next) => next - prev); + }); + + expect(count()).toBe(0); + }); + + it('should not silently replace object state with the raw emission when a reducer guard returns a falsy value', () => { + const state = signal({ age: 30 }); + + TestBed.runInInjectionContext(() => { + // reducer intentionally returns null to skip the update + connect(state, of({ age: 20 }), (prev, next) => + next.age > prev.age ? { age: next.age } : (null as any), + ); + }); + + expect(state()).toEqual({ age: 30 }); + }); + }); + describe('connects an observable to a signal not in injection context using injector', () => { @Component({ standalone: true, template: '' }) class TestComponent implements OnInit { diff --git a/libs/ngxtension/connect/src/connect.ts b/libs/ngxtension/connect/src/connect.ts index 75fbf4c65..d470663d4 100644 --- a/libs/ngxtension/connect/src/connect.ts +++ b/libs/ngxtension/connect/src/connect.ts @@ -120,7 +120,7 @@ export function connect(signal: WritableSignal, ...args: any[]) { const update = () => { signal.update((prev) => { if (!isObject(prev)) { - return reducer?.(prev, x) || x; + return reducer ? reducer(prev, x) : x; } if (!isObject(x)) { @@ -131,7 +131,7 @@ export function connect(signal: WritableSignal, ...args: any[]) { : reducedValue; } - const curr = reducer?.(prev, x) || x; + const curr = reducer ? reducer(prev, x) : x; if (isDate(curr)) { return new Date(curr);