Search code examples
sveltesvelte-3svelte-component

svelte - run code with side effects inside of for loop


I have the following Svelte component:

<script lang="ts">
    const tests = [ {txt: "aasdasdadss", foo: () => console.log("side ffect") }]
</script>
<div>
    {#each tests as test}
        <script>
            test.foo()
        </script>
        <div>{test.txt}</div>
    {/each}
</div>

Is there way to make test defined so, I can call foo?

This is closer, but it renders the null:

<script lang="ts">
    const tests = [ {txt: "aasdaasdasdsdadss", foo: null }]
    tests[0].foo = () => {
    }
</script>
<div>
    {#each tests as test}
        {
            test.foo() || null
        }
        <div>{test.txt}</div>
    {/each}
</div>

Solution

  • I think use:action might be what you are looking for REPL

    <script>
        const tests = [ {txt: "aasdaasdasdsdadss", foo: () => console.log("side ffect") }]
    </script>
    
    <div>
        {#each tests as test}        
            <div use:test.foo>{test.txt}</div>
        {/each}
    </div>