Home > Mobile >  Adding to nested JSON using svelte:self?
Adding to nested JSON using svelte:self?

Time:11-03

I'm trying to target nested JSON using svelte:self and encountering an issue where adding to the JSON will result in any newly added entries being deleted if they occur lower down the tree in the JSON structure. Here's an example REPL using the svelte:self demo. I'm clearly missing something with how I've specified where to add within the JSON?

<script>
let files = [
  {
    name: 'entry 1',
    files: [
      { 
        name: 'nested entry' 
      }
    ]
  },        
  { 
    name: 'entry 2' 
  }
];

function add() {
  files = files.concat({name: 'new item'})
}
</script>

<ul>
{#each files as file}
<li>
  {#if file.files}
    <svelte:self {...file}/>
  {:else}
    <File {...file}/>
  {/if}
</li>
{/each}
<li>
  <button on:click={() => add()}>new</button>
</li>
</ul>

CodePudding user response:

Instead of spreading the props in <svelte:self {...file}> setting them seperately and adding 'bind:' to the files there and in the main <Folder ..> tag seems to solve the unwanted deletions -> [REPL] (https://svelte.dev/repl/dfc42f18f777472bb2b1033f6b077c67?version=3.44.1)

App.svelte
<Folder name="Home" bind:files={root} expanded/>
Folder.svelte
<svelte:self name={file.name} bind:files={file.files}/>
  • Related