Skip to content

Commit

Permalink
fix: ensure SvelteMap reactivity persists through deriveds (#13877)
Browse files Browse the repository at this point in the history
* fix: ensure SvelteMap reactivity persists through deriveds

* fix: ensure SvelteMap reactivity persists through deriveds

* fix: ensure SvelteMap reactivity persists through deriveds
  • Loading branch information
trueadm authored Oct 24, 2024
1 parent 041e563 commit 5a54ad9
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 1 deletion.
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}

0 comments on commit 5a54ad9

Please sign in to comment.