Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/small-llamas-drum.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

fix: keep reactions up to date even when read outside of effect
2 changes: 1 addition & 1 deletion packages/svelte/src/internal/client/runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ export function update_reaction(reaction) {
reaction.deps = deps = new_deps;
}

if (is_updating_effect && effect_tracking() && (reaction.f & CONNECTED) !== 0) {
if (effect_tracking() && (reaction.f & CONNECTED) !== 0) {
for (i = skipped_deps; i < deps.length; i++) {
(deps[i].reactions ??= []).push(reaction);
}
Expand Down
25 changes: 25 additions & 0 deletions packages/svelte/tests/signals/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1418,6 +1418,31 @@ describe('signals', () => {
};
});

test('derived when connected should add new dependency to its reaction even when read outside effect', () => {
let count_a = state(0);
let count_b = state(0);
let which = state(true);
let double = derived(() => ($.get(which) ? $.get(count_a) * 2 : $.get(count_b) * 2));

render_effect(() => {
$.get(double);
});

return () => {
flushSync();
assert.equal($.get(double!), 0);

set(which, false);
$.get(double); // read before render effect has a chance to rerun
flushSync();
assert.equal($.get(double!), 0);

set(count_b, 1);
flushSync();
assert.equal($.get(double!), 2);
};
});

test('$effect.root inside deriveds stay alive independently', () => {
const log: any[] = [];
const c = state(0);
Expand Down
Loading