Skip to content

fix: ensure no data loss occurs when using reactive Set methods #11385

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 29, 2024
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/honest-pans-kick.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"svelte": patch
---

fix: ensure no data loss occurs when using reactive Set methods
11 changes: 8 additions & 3 deletions packages/svelte/src/reactivity/set.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,18 +51,23 @@ export class ReactiveSet extends Set {
// @ts-ignore
proto[method] = function (...v) {
get(this.#version);
// We don't populate the underlying Set, so we need to create a clone using
// our internal values and then pass that to the method.
var clone = new Set(this.values());
// @ts-ignore
return set_proto[method].apply(this, v);
return set_proto[method].apply(clone, v);
};
}

for (const method of set_like_methods) {
// @ts-ignore
proto[method] = function (...v) {
get(this.#version);

// We don't populate the underlying Set, so we need to create a clone using
// our internal values and then pass that to the method.
var clone = new Set(this.values());
// @ts-ignore
var set = /** @type {Set<T>} */ (set_proto[method].apply(this, v));
var set = /** @type {Set<T>} */ (set_proto[method].apply(clone, v));
return new ReactiveSet(set);
};
}
Expand Down
20 changes: 20 additions & 0 deletions packages/svelte/src/reactivity/set.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,23 @@ test('set.delete(...)', () => {

assert.deepEqual(Array.from(set.values()), [1, 2]);
});

test('set.forEach()', () => {
const set = new ReactiveSet([1, 2, 3, 4, 5]);

const log: any = [];

const cleanup = effect_root(() => {
render_effect(() => {
set.forEach((v) => log.push(v));
});
});

flushSync(() => {
set.add(6);
});

assert.deepEqual(log, [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6]);

cleanup();
});