svelte: how do svelte run function between if block?

Viewed 2484

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?

4 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.

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 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}

I understand the other answers give a suggestion to use best practices. However, to answer the general question of running or calling JS code in Svelte within the HTML portions of it can be done as follows.

<script>
...
</script>

<!-- HTML part -->
{functionCall() || ""}  <-- This avoids 'undefined' showing up in your markup!

Or alternatively,

<!-- HTML part -->
{"" ?? functionCall()}  <-- This avoids 'undefined' showing up in your markup!

Better yet, use the void operator. Using the void and the Nullish operator ensures that, even if your function returns a value, nothing is ever displayed in your markup.

<!-- HTML part -->
{void functionCall() ?? ""} <-- This avoids any sort of value from showing up in your markup!
Related