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 can I add item on the first index of svelte {#each} block

I add item to first position of a list. In {#each} section, loop the list and show each item with component. The source is here (REPL) and below.
Everytime I add item, it show different item i add on the bottom, despite of I add item on the top of list.

Does anyone know what cause this?

App.svelte

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

<script>
    import ListItem from "./listItem.svelte";
    let list = [
        {id : [1,2,3,4,5]},
        {id : [3,4,5,6,7]}
    ];
    
    function addItem(){
        list = [
            {id:[5,6,7,8,9]}
            , ...list
        ]
        console.log(list)
    }
</script>

<button on:click={addItem}>click</button>

{#each list as item}
    <ListItem data={item}/>
{/each}

listItem.svelte

<script>
export let data = {};
let ids = data.id.join(' ');
</script>

<div>
    {ids}
</div>

>Solution :

Svelte by default adds items at the end, to achieve the correct result you need to use a key that associates the data uniquely with components. Keys are defined in parentheses within the each and the item itself can be a valid key:

{#each list as item (item)}

Docs:

If a key expression is provided — which must uniquely identify each list item — Svelte will use it to diff the list when data changes, rather than adding or removing items at the end. The key can be any object, but strings and numbers are recommended since they allow identity to persist when the objects themselves change.

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