Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Svelte Each loop is not updated while object changed dynamically

When i'm trying to change data dynamically of the each loop variable is not refreshing the DOM elements. How I can redraw the each loop values

<script>
    // default messages object
     let messages =[{
    "name":"John",
    "message":"Hi",
         "checked": false
  },
  {
    "name":"Anthony",
    "message":"welcome",
         "checked": true
  },
  {
    "name":"David",
    "message":"thank you",
         "checked": false
  }]
 //click function to change the values dynamically 
function test(){
     messages.map(ob=>{
        ob.checked = true;
    })
    console.log(messages)
}
</script>

template code

<div>
    {#each messages as m}
    <div>{m.checked}
        <input type="checkbox" bind:checked={m.checked}>
            {m.name}
        </div>
    {/each}
    <br>
    <button on:click={()=>{test()}}> check all values</button>
</div>

link for snippet: https://svelte.dev/repl/887e7e2de4114ec1bb3625c264b9a62c?version=3.24.1

Any help would be appreciated! Thank you :)

like image 974
Harish98 Avatar asked Apr 23 '26 07:04

Harish98


1 Answers

You can't update an array/object just by changing its attribute in svelte.

A simple rule of thumb: the name of the updated variable must appear on the left hand side of the assignment.

Updating Arrays and Objects

like image 179
Zmen Hu Avatar answered Apr 25 '26 19:04

Zmen Hu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!