Levi Minton
Levi Minton

Reputation: 3

Is it possible to rerender/update an each block in Svelte when a variable changes?

So, I'm pretty new to svelte and very new to sveltekit, but ever since I started learning svelte I've always seemed to run into this problem one way or another.

Here, I have an each block:

{#each {length: wordLength} as _, i}

<button class={getGuessInfo(i).state}
        on:click={() => changeColor(index)}>{getGuessInfo(i).letter}
</button>

{/each}

And I want to basically have this be reactive to my getGuessInfo()'s return value. I get you can make a function reactive if it doesn't have any parameters, but I'm not sure how to / if it's even possible to if the function relies on an index value.

Here is the getGuessInfo() definition:

function getGuessInfo(index) {

  if (index > $Guess.length - 1) return {letter: "", state: LetterState.MISS}

  return $Guess[index]

}

This basically just returns a blank letter/state if the index is too high, and the letter/state of Guess at that position if not.

This works fine when I open the website, but changing the value of Guess yields no reactivity from the page.

Honestly, I'm so new to frameworks/web development in general that I'm not really sure what I want as a solution, but maybe something like just rerendering the component? Or just the each block? Not sure.

Thanks!

Well, I tried doing: $: $Guess && getGuessInfo() But that obviously didn't work

I previously just had an each block that was directly tied to Guess, as in: {#each $Guess as btn, index} And that worked fine

Thing is I want to constantly have 5 (or wordLength) buttons showing at all times, even if they're blank. That's why I tried using the function

Upvotes: 0

Views: 1131

Answers (2)

brunnerh
brunnerh

Reputation: 184376

The reactive attempt is not too far off, you probably could define the function reactively like this:

$: getGuessInfo = index =>
    index > $Guess.length - 1 ?
      { letter: "", state: LetterState.MISS } :
      $Guess[index];

This should cause it to be re-evalutated when $Guess changes.

(Ternary operator just for brevity, you could use a block & return statements.)

Upvotes: 2

Corrl
Corrl

Reputation: 7689

To make the result of a function call reactive, add the variable based on which it should update as parameter - in your case

getGuessInfo(i, $Guess)

(Would be cleaner to not only add it in the function call, but also in the function definition. But if the variable is in scope, that's not essential)

Upvotes: 1

Related Questions