Skip to content

Commit

Permalink
fix: effects dependencies aren't detected properly in some cases
Browse files Browse the repository at this point in the history
If the effect has conditions inside it, and some of the branches don't run on the first effect run, some signals don't add the effect to their subscribers list. This fix ensures that each time the effect runs, it adds itself as the `currentEffect`, so the accessed signals will add it to their subscribers list for future runs.
  • Loading branch information
StyleShit committed May 14, 2024
1 parent c70a754 commit 8153002
Showing 1 changed file with 18 additions and 12 deletions.
30 changes: 18 additions & 12 deletions src/signals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,18 +47,20 @@ export function createEffect(
cb: EffectCallback,
options: EffectOptions = { batch: true },
) {
const effectFn = options.batch ? debounce(cb) : cb;

currentEffect = effectFn;

try {
cb();
// eslint-disable-next-line no-useless-catch -- Intentionally rethrowing the error
} catch (e) {
throw e;
} finally {
currentEffect = null;
}
const wrappedEffect = debounceIf(() => {
currentEffect = wrappedEffect;

try {
cb();
// eslint-disable-next-line no-useless-catch -- Intentionally rethrowing the error
} catch (e) {
throw e;
} finally {
currentEffect = null;
}
}, options.batch);

wrappedEffect();
}

export function createMemo<T>(cb: () => T): () => T {
Expand All @@ -73,6 +75,10 @@ export function createMemo<T>(cb: () => T): () => T {
return value as () => T;
}

function debounceIf(effect: EffectCallback, condition: boolean) {
return condition ? debounce(effect) : effect;
}

function debounce<Args extends unknown[]>(
fn: (...args: Args) => unknown,
ms = 0,
Expand Down

0 comments on commit 8153002

Please sign in to comment.