svelte: how do svelte run function between if block?

im trying to put a function between if else block. below is what i imagine it would be.:

<script>
let condition=false
function_here(event){
   if(event){
      condition = true;
   }else if(!event){
      condition = false;
   }else{
      condition = !condition;
   }
</script>
{#each post as posts}
   {#if posts.object1==="match" }
      <p>HTML HERE</p>
      {function_here(true)}
   {/if}
{/each}
{#if condition}
   <button>type1</button>
{:else}
   <button>type2</button>
{/if}

if only during looping post result, if found posts.object1 match, i need to change the status of variable "condition"

however , this example return result "undefined".

How do i put function in between if block in svelte?

2 answers

  • answered 2020-09-14 05:26 Antony Acosta

    You are trying to approach this in a way that JSX would like. Why not abstract that logic into plain JS inside the <script> ?

    <script>
    let condition=false
    function_here(event){
       if(event){
          condition = true;
       }else if(!event){
          condition = false;
       }else{
          condition = !condition;
       }
    }
    
    for (post in posts) {
      if(post.object1 === 'match') {
        function_here(true)
      }
    }
    </script>
    {#each post as posts}
       {#if post.object1==="match" }
          <p>HTML HERE</p>
       {/if}
    {/each}
    {#if condition}
       <button>type1</button>
    {:else}
       <button>type2</button>
    {/if}
    

    let me know if this helps you

  • answered 2020-09-14 07:01 Stephane Vanraes

    Calling functions inside the template like that is considered bad practice in Svelte, that code belongs in the script part of the component. The best approach this problem is a reactive variable so that it also changes if posts changes:

    $: condition = posts.... // something based on posts
    

    What condition actually works out to be is up to you though, the code you gave in your answer seems very simplified from the actual code.