Search code examples
statesveltereactive

reactive statement that runs every time any state variable changes


I am trying to write a simple app. The app has two child components. Each components represents a team. The score begins from 20 and the group which loses all points 0 lost.

my parent component has two variables

  <script>
    let scoreA = 20
    let scoreB = 20
  </script>

the child components are simple counter components, which have one variable called score and increment and decrement function. I am binding the two state variables from the parent the the child components and passing the state from the child to the parent

<CounterComponent bind:score={scoreA} />
<CounterComponent bind:score={scoreB} />

I tried to make a function which constantly checks the state every time something changes using a reactive statement:

  <script>
    let scoreA = 20
    let scoreB = 20
    function checkState() {
      console.log(`Score A: ${scoreA}, Score B: ${scoreB}`)
    }
    $: checkState()
  </script>

For some reason this function only runs one time and that is it. Why is this happening and how can I fix this?

Thanks for the help.


Solution

  • Reactive dependencies are only tracked in the statement itself; because you just call a function without any arguments, it detects no dependencies.

    You either have to declare the function reactively or just inline the code. You can also create reactive statements with blocks using $: { ... } if you need multiple statements.

    Since it is just one line, you could just inline it here:

    $: console.log(`Score A: ${scoreA}, Score B: ${scoreB}`)
    

    Keeping the function, but making it reactive:

    $: checkState = function () {
        console.log(`Score A: ${scoreA}, Score B: ${scoreB}`)
    }
    $: checkState()
    

    Here the call has a transitive dependency on the scores.