Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Svelte Store: Am I missing the point of the stores subscribe method?

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.

like image 890
JustBarnt Avatar asked Nov 27 '25 17:11

JustBarnt


1 Answers

.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())

REPL

<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
like image 76
Corrl Avatar answered Dec 02 '25 04:12

Corrl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!