title: Svelte: using "bind:this" inside "each" block
body: <p>I want to render an array of objects, using an <code>each</code> block. I need to be able to remove elements from the array using callbacks from inside the <code>each</code> block. Also, for more complex UI-interactions, I need the reference to each component of the <code>each</code>-block to be available in the main app.</p>
  <p>Here is my approach:</p>
  <pre class="lang-html prettyprint-override"><code>&lt;script&gt;
      let items = [{text: &quot;one&quot;}, {text: &quot;two&quot;}];
      
      function deleteItem(i) {
          items.splice(i, 1);
          items = items;
      }
  &lt;/script&gt;
  
  {#each items as item, i}
  &lt;button bind:this={items[i].ref} on:click={() =&gt; deleteItem(i)} &gt;
      {item.text}
  &lt;/button&gt;   
  &lt;p /&gt;
  {/each}
  </code></pre>
  <p>Understandibly, this leads to errors such as <code>item[i] is undefined</code>, because when the splicing of <code>items</code> is processed, the <code>bind:this</code> cannot properly be cleaned up anymore.</p>
  <p>I tried to solve this by moving the component-references to a separate array. But no matter what I try, I cannot get the reference-array and the object-array to sync: Whenever <code>deleteItem()</code> is processed, I end up with <code>null</code>-values inside the <code>refs</code>-array. Here is one of my approaches (the <code>each</code>-section that prints the <code>refs</code>-array should help to show the <code>null</code>-values):</p>
  <pre class="lang-html prettyprint-override"><code>&lt;script&gt;
      import {tick } from &quot;svelte&quot;;
      let items = [{text: &quot;one&quot;, id: 1}, {text: &quot;two&quot;, id:2}];
      let refs = [];
      
      async function deleteItem(i) {
          items.splice(i, 1);
          await tick();
          refs.splice(i, 1);
          items = items;
          console.log(refs);
      }
  &lt;/script&gt;
  
  {#each items as item, i (item.id)}
  &lt;button on:click={async () =&gt; deleteItem(i)} bind:this={refs[i]}&gt;
      {item.text}
  &lt;/button&gt;   
  &lt;p /&gt;
  {/each}
  
  {#each refs as ref}
  {ref}
  &lt;p /&gt;
  {/each}
  </code></pre>
  <p>I tried with and without <code>tick()</code>, tried inserting the <code>tick()</code> in different places, with and without <code>async</code> and with and without using <code>(item.id)</code> in the each block. How can I keep the references and the data in sync?</p>