Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Variable change doesn't render in the view

The intention of the following code is to display a row if unique identifier of the row above is within the rows array. Why does Svelte update the view only after several clicks, in a seemingly random way?

<script>
    import { onMount } from "svelte";

        let rows = [
            {"name": "Alex", "id": "0"},
            {"name": "Steve", "id": "1"},
            {"name": "Mike", "id": "2"},
        ]; 
    
    let expandedRows = [];
    
    function toggleExpandRows(row_id_to_toggle) {
            console.log("Row to toggle:", row_id_to_toggle)
            console.log(expandedRows);
      if (expandedRows.includes(row_id_to_toggle)) {
                console.log(expandedRows, "includes", row_id_to_toggle)
        expandedRows = expandedRows.filter(expanded_row_id => expanded_row_id !== row_id_to_toggle)
      } else {
        expandedRows.push(row_id_to_toggle);
      }
    }

</script>

<div class="overflow-x-auto w-full">
  <table class="table table-compact w-full">
    <thead>
      <tr>
        <th></th>
        <th>Name</th>
      </tr>
    </thead>
    <tbody>
      {#each rows as row (row.id)}
        <tr>
          <td>
            <button class="btn btn-xs" on:click={()=>toggleExpandRows(row.id)}>+/-</button>
          </td>
          <td class="min-w-[3rem] ">{row.name}</td>
        </tr>
            row.id: {JSON.stringify(row.id)}
        {#if expandedRows.includes(row.id)}
          <tr>
            <td colspan="2">-</td>
          </tr>
        {/if}

      {/each}
    </tbody>
  </table>
  Expanded: {JSON.stringify(expandedRows)}
</div>

REPL

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Reactivity is based on assignments, which is why for arrays you also often see this pattern instead of push:

array = [...array, item];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading