Ralph
Ralph

Reputation: 1

Having problems with a reactive list in Svelte

I am new to Svelte and I am stuck with a list that is not reacting to user input.

Here is my situation simplified:

Problem: When I change the values in the Input Element, the list in App.svelte won't update.

Code:

App.svelte

<script>
    import Nested from './Nested.svelte';
    
    let customers=[{
        id:1,
        name: "Smith"
    },{
        id:2,
        name: "Foo"
    },{
        id:3,
        name: "Bar"
    }]
</script>

{#each customers as customer (customer.id)}
    <p>{customer.name}</p>
{/each}

<Nested {customers}/>

Nested.svelte:

<script>
    export let customers;
</script>

{#each customers as customer (customer.id)}
    <p><input bind:value={customer.name} /></p>
{/each}

Link to REPL: https://svelte.dev/repl/fb22de4557744d8b8f4410f21402efca?version=3.32.3

What am I doing wrong?

Upvotes: 0

Views: 859

Answers (1)

Geoff Rich
Geoff Rich

Reputation: 5482

Svelte won't automatically update a prop in the parent when you update it in the child. You will need to opt-in to this two-way binding using the bind directive. It works similarly to the value binding you used on the <input>.

{#each customers as customer (customer.id)}
    <p>{customer.name}</p>
{/each}

<Nested bind:customers/>

Upvotes: 2

Related Questions