Search code examples
sveltesveltekitsvelte-component

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

<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.