user2915010
user2915010

Reputation: 47

Binding Nested Object Select Svelte

I am trying to create a dynamic Fieldset form data but the select input wont change the binded data

Image of Test

I made this Repl https://svelte.dev/repl/0dff600bd5134fb59d19e6ca4cb98fe6?version=3.48.0

<script>
    import Fieldset from "./Fieldset.svelte"
    let name = 'world';
    let fields = {Connection: {Setting1 : 1, Setting2 : 2 }}
</script>

<h1>Hello {name}!</h1>

<Fieldset bind:fields={fields.Connection}/>
<button on:click={()=> console.log(fields) }>
    Button
</button>

then my Fieldset

 <script>
        import Field from "./Field.svelte"
        export let fields;
    </script> 
    <form>
        {JSON.stringify(fields)}
        {#each Object.entries(fields) as [ValueTitle, Value]}
            <div class="mb-4 items-center">
                <label for={ValueTitle}>{ValueTitle} </label>
                Fieldset:{Value}
                <Field bind:dataValue={Value} />
            </div>
        {/each}
    </form>

Field:

 <script>
    import Selector from "./Selector.svelte"
    export let dataValue;
    let options = {Hans: 1, Christian: 2, Andersen:3};
</script>
Field:{dataValue}
<Selector
    bind:data={dataValue}
    options={options}
/>

Last The selector

 <script>
 export let data;
 export let options;
 </script>
    
  <select
  bind:value={data}    
  >
  {#each Object.entries(options) as [k, val]}
     <option class="p-2" value={val}>{k}</option>
  {/each}
  </select>

The Data changes in the First Layer but not all the way Why is that and what am i dooing wrong

Upvotes: 0

Views: 1711

Answers (1)

brunnerh
brunnerh

Reputation: 185225

Using Object.entries creates new objects which are detached from the source. If you modify the primitive results of that, the source object will not be affected.

If you want to modify an object's properties, you have to pass in the object as a whole/use the object with a property path or index.

E.g.

<!-- In Fieldset -->
{#each Object.keys(fields) as key}
    <div class="mb-4 items-center">
        <label for={key}>{key}</label>
        Fieldset:{fields[key]}
        <Field bind:dataValue={fields[key]} />
    </div>
{/each}

Upvotes: 1

Related Questions