How can I re-render a view after deleting an object from an array, in Svelte?

1.6k views Asked by At

I am working on a small Svelte application, for learning purposes (Im new to Svelte). The application uses an array of objects displayed in a view as an HTML table:

let countries = [
    { code: "AF", name: "Afghanistan" },
    { code: "AL", name: "Albania" },
    { code: "IL", name: "Israel" }
]; 

<table class="table table-bordered">
  <thead>
    <tr>
      <th>#</th>
      <th>Code</th>
      <th>Name</th>
      <th class="text-right">Actions</th>
    </tr>
  </thead>
  <tbody>
    {#if countries.length}
     {#each countries as c, index}  
      <tr>
       <td>{index+1}</td>
       <td>{c.code}</td>
       <td>{c.name}</td>
       <td class="text-right">
        <button data-code="{c.code}" on:click="{deleteCountry}" class="btn btn-sm btn-danger">Delete</button>
       </td>
      </tr>
     {/each}
    {:else}
    <tr>
      <td colspan="4">There are no countries</td>
    </tr>
    {/if}
  </tbody>
</table>

I am doing a delete operation this way:

function deleteCountry(){
    let ccode = this.getAttribute('data-code');
    let itemIdx = countries.findIndex(x => x.code == ccode);
    countries.splice(itemIdx,1);
    console.log(countries);
}

There is a REPL here.

The problem

I have been unable to render the table (view) again, after the countries array is updated (an element is deleted from it).

How do I do that?

2

There are 2 answers

0
Kokizzu On BEST ANSWER

add

countries = countries;

after this line

countries.splice(itemIdx,1);

since reactivity/rerendering/UI update only marked after assignment.

0
cyr_x On

For svelte to pick up the change to your array of countries, you need to create a new reference of the array. For this you could use the Array.filter method.

<script>
    let countries = [
     { code: "AF", name: "Afghanistan" },
     { code: "AL", name: "Albania" },
     { code: "IL", name: "Israel" }
    ];
    
    function deleteCountry(code) {
        countries = countries.filter(c => c.code !== code)
    }
</script>

<table class="table table-bordered"> 
  <thead>
    <tr>
      <th>#</th>
      <th>Code</th>
      <th>Name</th>
      <th class="text-right">Actions</th>
    </tr>
  </thead>
  <tbody>
    {#if countries.length}
    {#each countries as c, index}   
    <tr>
      <td>{index+1}</td>
      <td>{c.code}</td>
      <td>{c.name}</td>
      <td class="text-right">
        <button on:click="{() => deleteCountry(c.code)}" class="btn btn-sm btn-danger">Delete</button>
      </td>
    </tr>
    {/each}
    {:else}
    <tr>
      <td colspan="4">There are no countries</td>
    </tr>
    {/if}
  </tbody>
</table>

Also you can directly use the country code as an argument for the deleteCountry method.