1

I created a REPL to illustrate my issue. So I have an array with elements and those elements bind there properties to input fileds. But changing those values does nothing. On log or add all changes get lost.

Thanks in advance

I tried adding a id prop to Item

1 Answer 1

1

You need to pass reference data types (array or object) - here arrayItem for the update to happen, since the update always points to the same reference in memory.

In your example, you are passing primitive types (number and string) - here x and y, these have new memory locations when created, so the update is not done on all locations!

item

<script>
    export let arrayItem;
</script>

<div>
    <input bind:value={arrayItem.x}>
    <input bind:value={arrayItem.y}>
</div>

parent

<script>
    import Item from "./Item.svelte"
    
    let array = [
        {
            x: 1, 
            y: 2
        }
    ];

    function handleAdd() {
        array = [...array, { x: 0, y: 0 }];
    }

    function handleLog() {
        console.log(array);
    }
</script>

<div>
    {#each array as arrayItem}
        <Item {arrayItem} />
    {/each}
    <button on:click={handleAdd}>add element to array</button>
    <button on:click={handleLog}>log array</button>
</div>

repl example

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.