Skip to content

Commit

Permalink
fix: computed was not activating if its value started as undefined
Browse files Browse the repository at this point in the history
  • Loading branch information
jmeistrich committed Oct 2, 2023
1 parent 60326cd commit 88502c5
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
5 changes: 4 additions & 1 deletion src/observe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export function observe<T>(
options = reactionOrOptions;
}
let dispose: (() => void) | undefined;
let isFirstRun = true;
const e: ObserveEventCallback<T> = { num: 0 };
// Wrap it in a function so it doesn't pass all the arguments to run()
const update = function () {
Expand Down Expand Up @@ -55,7 +56,7 @@ export function observe<T>(
}

// 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);
}

Expand All @@ -66,6 +67,8 @@ export function observe<T>(
e.num++;

endBatch();

isFirstRun = false;
};

update();
Expand Down
13 changes: 13 additions & 0 deletions tests/computed.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean[]>(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);

Expand Down
6 changes: 3 additions & 3 deletions tests/react.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -676,7 +676,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() {
Expand All @@ -693,8 +693,8 @@ describe('useObserve', () => {
}
render(createElement(App));

expect(num).toEqual(1);
expect(numSets).toEqual(0);
expect(num).toEqual(2);
expect(numSets).toEqual(1);
});
});

Expand Down

0 comments on commit 88502c5

Please sign in to comment.