sveltejs / svelte

Cybernetically enhanced web apps
https://svelte.dev
MIT License
78.73k stars 4.13k forks source link

Svelte 5: Reactivity with `Set`s and `Map`s and `$state` #13570

Closed nvlang closed 2 hours ago

nvlang commented 2 hours ago

Describe the bug

I noticed that the $state rune doesn't work as expected for objects of type Map or Set. In particular, there doesn't seem to be any reactivity when declaring something like const map = $state(new Map()) and then updating map.

Apologies if this is by design, I couldn't find documentation about it or another issue describing this behavior.

Reproduction

Link to reproduction in REPL

This is the gist of it:

For Sets:

<script>
    let set = $state(new Set());

    function onclick() {
        if (set.has(1)) set.delete(1);
        else set.add(1);
    }
</script>

<button {onclick}>
    {set.has(1)}
</button>

For Maps:

<script>
    let map = $state(new Map([[1, false]]));

    function onclick() {
        if (map.get(1)) map.set(1, false);
        else map.set(1, true);
    }
</script>

<button {onclick}>
    {map.get(1)}
</button>

Logs

No response

System Info

N/A (REPL).

Severity

annoyance

brunnerh commented 2 hours ago

$state does not affect classes, there are reactive versions of built-ins like Set and Map that can be imported from 'svelte/reactivity'.

Conduitry commented 2 hours ago

https://svelte-5-preview.vercel.app/docs/runes#$state Yup. $state only makes POJOs deeply reactive, and there are reactive versions of these other types of objects.

nvlang commented 2 hours ago

Ah, my bad, sorry I missed that. Thank you!