Search code examples
javascriptsvelte

Cannot access to values in store of Map in Svelte


I have simple store of new Map() and I like to iterate it in Svelte component. In the {#each} block i can see it iterates as many times as Map has elements but I can't see values.

<script>
    import {items} from "./store.js"

    $items.set("one", { name: "John", age: 50 })
    $items.set("two", { name: "Jack", age: 25 })
</script>

<h1>Hello!</h1>
{#each $items as item}
    <div>name: {item.name}</div>
{/each}
// store.js
import {writable, get} from "svelte/store"

export let items = writable(new Map())

Playground.


Solution

  • If you iterate a Map you get [key, value] objects, so you need:

    {#each $items as [key, value]}
        <div>name: {value.name}</div>
    {/each}
    

    If you only need the keys or the values, there are also the respective functions keys()/values(), so for the given code you could use:

    {#each $items.values() as item}
        <div>name: {item.name}</div>
    {/each}
    

    Also, Map is not reactive, so unless you trigger the store manually, later modifications will not update the UI. Svelte 5 has a reactive version of Map in svelte/reactivity.