Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't understand how reactivity and stores work

I’m trying to understand how reactivity should work, but I cannot figure out why some things work how they work.

Svelte REPL with the code: https://svelte.dev/repl/aa0821cd95c54708b2d12a05bf74577e?version=3.49.0

I created a simple app:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

App.svelte:

<script>
    import { numbers } from './store.js'
    
    function copy() {
        $numbers.copied = $numbers.selected
    }
    
    function select(i) {
        console.log("Selected: " + i)
        $numbers.selected = i
    }
</script>

<button on:click={select(1)}>
    1
</button>
<button on:click={select(2)}>
    2
</button>
<button on:click={select(3)}>
    3
</button>

<button on:click={copy()}>
    Copy
</button>

<h1>
    Selected: {$numbers.selected}
</h1>
<h1>
    Copied: {$numbers.copied}
</h1>

store.js:

import { writable } from 'svelte/store'

export let numbers = writable({
    selected: null,
    copied: null
})

From this, I was expecting:

  1. On launch, store values stay as null
  2. On every button click, $store.selected changes to proper value
  3. $store.copied updates its value only when Copy button is clicked

Instead:

  1. On launch, select function is called 3 times, once for every button with its argument
  2. $store.selected and $store.copied both have value 3 which cannot be changed by clicking buttons
  3. When clicking buttons, select function is not called

>Solution :

Your event handlers are just wrong. You are calling the functions instead of passing them.

You need something like on:click={() => select(1)}. For copy you could also pass it as is because it has no arguments: on:click={copy}.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading