10

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 :)

2 Answers 2

12

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

Sign up to request clarification or add additional context in comments.

1 Comment

An actual example might help here. The documentation does not provide an example of this scenario
2

map returns a new array, in your case you got a new array from undefined, you need assign the result and correctly return the new object

function test(){
    messages = messages.map(obj => ({
        ...obj,
        checked: true
    }));
}

1 Comment

messages = [...messages];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.