Jan Vladimir Mostert
Jan Vladimir Mostert

Reputation: 13002

Svelte #each not looping through data

i'm taking SveleteJS for a test drive and got stuck

Made a Dashboard component and inside that component, i placed a Whiteboard component:

<script>
    import Whiteboard from "./Whiteboard.svelte";
    export let name;
</script>

<div class="box part-of-dashboard">
    <Whiteboard lines={[]} />
</div>

Whitebord.svelte:

<script>
    export let lines = [];

    export function addLine() {
        lines.push("blah");
        console.log(lines);
    }

</script>

<div style="background-color:red">
    {#each lines as line}
        <div>
            {line}
        </div>
    {/each}
</div>
<div>
    <button on:click={addLine}>
        Add Line
    </button>
</div>

When i click the button, the console.log triggers and i can see the lines increasing in size, but i don't see it being rendered on the page, just the empty red div wrapping it.

I've tried adding $: to various places, but i'm not yet sure where it should be used and where it shouldn't be used, not that it was making a difference.

How do i get that #each to render a list of divs (and also, what is the correct way to pass in data from the on:click, doing {addLine('blah')} executes that addLine on page load)?

Upvotes: 2

Views: 4518

Answers (1)

Joshua T
Joshua T

Reputation: 2599

So, this kind of goes against what one might expect, but Svelte does not detect [].push() as mutating the state of the array variable. This is why the console log shows the variable being updated, but Svelte's rendering does not respond.

After doing a little digging, I found several threads (1, 2) that point this out, and clarify that this is true for calling methods on any object.

EDIT: This is also now called out explicitly in the docs / tutorials - see "Updating Arrays and Objects"

One of the easiest solutions (per the linked threads and docs) is to simply re-assign the variable value to itself; Svelte will pick that up and re-render. So, in your scenario, all I had to do to get your code to work was replace this:

export function addLine() {
    lines.push("blah");
    console.log(lines);
}

With:

export function addLine() {
    lines.push("blah");
    lines = lines;
    console.log(lines);
}

Upvotes: 9

Related Questions