Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

svelte: how do svelte run function between if block?

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

<script>
let condition=false
function 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?

like image 464
dwerty_weird Avatar asked Jan 24 '23 18:01

dwerty_weird


1 Answers

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.

like image 91
Stephane Vanraes Avatar answered Jan 30 '23 12:01

Stephane Vanraes