BlackFur
BlackFur

Reputation: 328

Accessing Store's value inside loop in SvelteJS v3

i am building a dashboard from an array of objects that have store as some of its property. each store are updated independently from different source.

my problem is i am unable to read the store value inside each loop.

to simplify the following code sample, i use tweened instead of store

the following code also available in Svlete REPL https://svelte.dev/repl/9a17102e7d32471a940ba007e5b56db0?version=3.6.7

<script>
    import { tweened } from 'svelte/motion';

    const data = [{
        label: 'one',
        value: tweened(0)
    }, {
        label: 'two',
        value: tweened(0)
    }]

</script>

<ul>
    {#each data as item}
        <li>{item.label} ({item.$value})</li>
    {/each}
</ul>

the {item.$value} part returns undefined

Upvotes: 3

Views: 1281

Answers (1)

Rich Harris
Rich Harris

Reputation: 29605

This isn't currently possible — there's an issue open for 'contextual stores' (#2016) which would let you do this sort of thing...

<ul>
  {#each data as { label, value }}
    <li>{label} ({$value})</li>
  {/each}
</ul>

...but we're not there yet. In the meantime the workaround is to pass the store to a component:

<ul>
  {#each data as item}
    <ListItem label={item.label} value={item.value}/>
  {/each}
</ul>

Inside the component, you'd have export let label, value, and you could use $value as intended.

Upvotes: 6

Related Questions