Search code examples
svelte-3

How to pop array while looping with each in Svelte?


<script> 
   let myMessages = ["msg1", "msg2", "msg3"]
</script>

{#each myMessages as message}
    <div>{message}</div>
{/each}

I would like to remove each element from myMessages once it has been added on DOM so at the end myMessages is empty?
(a variation on this would be to add a {#if} condition in the loop and remove only if element satisfy this condition)


Solution

  • In absence of feedback on DOM rendering I would assume it. So, to render msg1 and pop it afterwards, I would proceed as follows:

    <script> 
      let myMessages = []
      let tmpMessages = myMessages
      # then add msg1 to myMessages, render it and pop it
      myMessages.push("msg1")
      tmpMessages = myMessages
      myMessages.pop()
    </script>
    
    {#each tmpMessages as message}
      <div>{message}</div>
    {/each}