Skip to content
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

fix: ensure SvelteMap reactivity persists through deriveds #13877

Merged
merged 3 commits into from
Oct 24, 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/hungry-dogs-happen.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

fix: ensure SvelteMap reactivity persists through deriveds
11 changes: 10 additions & 1 deletion packages/svelte/src/reactivity/map.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,22 @@ export class SvelteMap extends Map {
var s = sources.get(key);
var prev_res = super.get(key);
var res = super.set(key, value);
var version = this.#version;

if (s === undefined) {
sources.set(key, source(0));
set(this.#size, super.size);
increment(this.#version);
increment(version);
} else if (prev_res !== value) {
increment(s);
// If no one listening to this property and is listening to the version, or
// the inverse, then we should increment the version to be safe
if (
(s.reactions === null && version.reactions !== null) ||
(s.reactions !== null && version.reactions === null)
) {
increment(version);
}
}

return res;
Expand Down
13 changes: 13 additions & 0 deletions packages/svelte/tests/runtime-runes/samples/derived-map/_config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { flushSync } from 'svelte';
import { test } from '../../test';

export default test({
html: `Loading`,

async test({ assert, target }) {
await Promise.resolve();
flushSync();

assert.htmlEqual(target.innerHTML, `1`);
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<script>
import { untrack } from 'svelte';
import { SvelteMap } from 'svelte/reactivity';

const cache = new SvelteMap();

function get_async(id) {
const model = cache.get(id);

if (!model) {
const promise = new Promise(async () => {
await Promise.resolve();
cache.set(id, id.toString());
}).then(() => cache.get(id));

untrack(() => {
cache.set(id, promise);
});

return promise;
}

return model;
}

const value = $derived(get_async(1));
</script>

{#if value instanceof Promise}
Loading
{:else}
{value}
{/if}