diff --git a/src/observe.ts b/src/observe.ts index b6268e0a4..ea91d1966 100644 --- a/src/observe.ts +++ b/src/observe.ts @@ -27,6 +27,7 @@ export function observe( options = reactionOrOptions; } let dispose: (() => void) | undefined; + let isFirstRun = true; const e: ObserveEventCallback = { num: 0 }; // Wrap it in a function so it doesn't pass all the arguments to run() const update = function () { @@ -57,7 +58,7 @@ export function observe( endBatch(); // Call the reaction if there is one and the value changed - if (reaction && (e.num > 0 || !isEvent(selectorOrRun as any)) && e.previous !== e.value) { + if (reaction && (e.num > 0 || !isEvent(selectorOrRun as any)) && (isFirstRun || e.previous !== e.value)) { reaction(e); } @@ -66,6 +67,8 @@ export function observe( // Increment the counter e.num++; + + isFirstRun = false; }; update(); diff --git a/tests/computed.test.ts b/tests/computed.test.ts index 31f0a44e2..6263e4d09 100644 --- a/tests/computed.test.ts +++ b/tests/computed.test.ts @@ -258,6 +258,19 @@ describe('Two way Computed', () => { expect(obs.test.get()).toEqual(true); expect(obs.test2.get()).toEqual(false); }); + test('Computed activates when undefined', () => { + const obs = observable(undefined); + const comp = computed(() => { + return obs.get()?.filter((a) => !!a); + }); + let observed: boolean[]; + observe(() => { + observed = comp.get(); + }); + expect(observed!).toEqual(undefined); + obs.set([]); + expect(observed!).toEqual([]); + }); test('Two way computed value is set before calling setter', () => { const obs = observable(0); diff --git a/tests/react.test.ts b/tests/react.test.ts index 1f01ea350..6427d9823 100644 --- a/tests/react.test.ts +++ b/tests/react.test.ts @@ -647,7 +647,7 @@ describe('useObserve', () => { expect(num).toEqual(2); expect(numSets).toEqual(1); }); - test('useObserve with undefined never calls reaction', () => { + test('useObserve with undefined calls reaction once', () => { let num = 0; let numSets = 0; function Test() { @@ -664,8 +664,8 @@ describe('useObserve', () => { } render(createElement(App)); - expect(num).toEqual(1); - expect(numSets).toEqual(0); + expect(num).toEqual(2); + expect(numSets).toEqual(1); }); });