Home > Blockchain >  Update global variable each run through each loop and entering an if-block in svelte
Update global variable each run through each loop and entering an if-block in svelte

Time:12-23

I have this kind of code

<script>
    let name = 'world';
    let counter = 5
    function updateCounter(){
        counter   
    }
</script>

{#each Array(3) as _, i}
<div>
    {#if i % 2 === 0}
        {updateCounter()}
    {/if}
    {i} : {counter}
</div>
{/each}

to test here: https://svelte.dev/repl/fa15a13afb9c4896bb06b53be545365d?version=3.55.0

which gives me this output:

[![enter image description here][1]][1]

While what I would like to have is this:

0 : 6
1 : 6
2 : 7

Is there any way to update the counter when I enter the if-condition? I tried many things and at this Point I am just confused and would appreciate any help!:) [1]: https://i.stack.imgur.com/JhI65.png

CodePudding user response:

Everything between {} in the markup will be rendered as a text node. Since the value returned from updateCounter() is undefined that will be rendered in the DOM.

You could do the calculation inside the markup directly instead.

Example (REPL)

<script>
    let counter = 5;
</script>

{#each Array(3) as _, i}
    <div>
        {i} : {counter   Math.floor(1   i/2)}
    </div>
{/each}

CodePudding user response:

You are not supposed to mutate state in an #each at all.

When and how often the expressions are executed is not necessarily deterministic/defined; you should abandon this approach.

  • Related