javascriptdictionarysvelte

SvelteMap not reactive


I'm trying to use SvelteMap: https://svelte.dev/docs/svelte/svelte-reactivity#SvelteMap

but for some reason it's not reactive.

I am exporting it from a .svelte file:

export const items = new SvelteMap<number, Item>();

Item is an object.

Then inside a function I change the contents, like:

const item = items.get(num);
item.someProp = newValue;

The map is update, but reactivity doesn't work in components.

I also tried to re-assign the item in that function

const item = items.get(num);
item.someProp = newValue;
items.set(num, item);

still no go..


Solution

  • The map will not make its contents reactive, just its own properties and methods.

    So the items you put into the map need to be stateful, e.g.

    const item = $state({ value: 1 });
    items.set(0, item);
    

    Playground

    (For plain objects and arrays, $state creates a proxy wrapper around the object which will fire signals that trigger reactivity on change. Class instances with $state properties would work as well.)

    If you cannot make the item reactive (e.g. because it is from a separate library), you could wrap the instance in an object and assign a new wrapper after the modification to trigger the reactivity of the map.

    const { current } = items.get(num);
    current.someProp = newValue;
    items.set(num, { current }); // constructs new object
    

    Playground