Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading