I am learning Svelte and attempting to build a simple SPA. So far the biggest thing that doesn't make any sense to me is the subscribe method for stores. In all of the examples on svelte.dev its only used to link to an unsubscribe method for when a component is unMounted/Destroyed.
On top of that, when I create my store I have done this.
import { writable } from 'svelte/store'
const store = writable(0);
function Notify()
{
store.subscribe(value => console.log(value));
}
function DoThing(newValues)
{
store.update(oldValues => oldValues = newValues);
Notify();
}
But in my logs, it still runs twice. Even though I am only calling it after my store.update
call.
Would greatly appreciate any explanations on what I could be misunderstanding or doing incorrectly.
.subscribe()
only has to be called once - then the subscription is active. So in your case you don't need Notify()
(Since you don't modify the current value but only want to set a new one, you can use .set()
instead of .update()
)
<script>
import { writable } from 'svelte/store'
const store = writable(0);
store.subscribe(value => console.log(value));
function doThing(newValue) {
store.set(newValue)
}
</script>
<button on:click={() => doThing(Math.random())}>
doThing
</button>
Calling .subscribe()
returns a function which can be used to cancel the subscription
const unsubscribe = count.subscribe(value => {
console.log(value);
});
unsubscribe(); // subscription canceled