Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update rendered content when my variable changes in Svelte/Svelte Kit

I have a simple svelte page in sveltekit:

<script>
    let array = [1, 2, 3, 4, 5];
</script>

{#each array as item}
    <li>{item}</li>
{/each}

<button
    on:click={() => {
        array.push('4');
        console.log(array);
    }}>Click Me</button
>

Pretty simple concept. When I update my array, I want the content on the page to be updated as well. Can someone help me on the road to figuring out what I need to do this? Thanks IA!

PS-- The array is successfully updating on the button click

like image 685
Newbie Avatar asked Oct 28 '25 02:10

Newbie


1 Answers

Svelte's reactivity is triggered by assignments, so if you push to an array you must write array = array after it to tell the Svelte compiler it has changed.

Example (REPL)

<script>
    let array = [1, 2, 3, 4, 5];
</script>

{#each array as item}
    <li>{item}</li>
{/each}

<button
    on:click={() => {
        array.push('4');
        array = array;
    }}
>
    Click Me
</button>
like image 86
Tholle Avatar answered Oct 29 '25 20:10

Tholle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!