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:
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:
- On launch, store values stay as null
- On every button click,
$store.selectedchanges to proper value $store.copiedupdates its value only when Copy button is clicked
Instead:
- On launch,
selectfunction is called 3 times, once for every button with its argument $store.selectedand$store.copiedboth have value 3 which cannot be changed by clicking buttons- When clicking buttons,
selectfunction 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}.