'How to animate array values in svelte with tweened store?

I have a writable store with following data

   let array= writable({
                          skills: [{
                                    id: 1,
                                    name: "Wordpress",
                                    knowledge: 0.9
                                   }, 
                                   {
                                    id: 2,
                                    name: "Js",
                                    knowledge: 0.8
                                     } ]
                      })

I want to animate progress bar according to KNOWLEDGE, im accessing knowledge in {#each } loop, but bar is not animated, beacause i have to pass tweened store object and set it value. So how to animate bar ? how to pass knowledge value in to tweened object set() method in loop ?



Solution 1:[1]

Each record in the array needs a corresponding tweened() store. You can create a component to do this for you.

  1. Create a component that wraps <progress/> and has a tweened() store:
<!-- SkillProgress.svelte -->
<script>
    import {tweened} from 'svelte/motion'

    export let value = 0

    const progress = tweened(0)

    progress.set(value)
</script>

<progress value={$progress}/>
  1. In App.svelte, bind a <SkillProgress/> component for each skill record:
<!-- App.svelte -->
<script>
  import SkillProgress from './SkillProgress.svelte'
  import {writable} from 'svelte/store'

  const skills = writable([{
            id: 1,
            name: "Wordpress",
            knowledge: 0.9
        }, 
        {
            id: 2,
            name: "Js",
            knowledge: 0.8
        }])
</script>

<ul>
    {#each $array.skills as skill}
        <li>
            {skill.name}
            <SkillProgress value={skill.knowledge}/>
        </li>
    {/each}
</ul>

Solution 2:[2]

Just to add on to the answer by joshnuss above.

SkillProgress.svelte needs one change:

progress.set(value) should be $: progress.set(value)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 joshnuss
Solution 2 Reidon