Svelte store subscribed function should not be invoked on subscription

Viewed 1673

I don't understand this. I am trying to subscribe to a svelte store. But the closure function which is being passed to subscribe is being immediately invoked. Even though the value of the store hasn't changed.

Here's a svelte REPL example

with the following code:

<script>
    import { onDestroy } from 'svelte';
    import { writable } from 'svelte/store';
    
    const store = writable({ givenName: '', familyName: '' });
    
    const unsubscribe = store.subscribe( state => {
    console.log('This function shouldn\'t have been invoked on subscription.');
    });
    onDestroy(unsubscribe);
</script>

<h1>
    Please check the console output ...
</h1>

IMHO, the closure function should be fired on change and not on subscriptionn or is there something I am missing?

2 Answers

A writable store will immediately invoke the function that is handed to subscribe with its current value. This is "works as designed". If you only care about updates you need to write a small wrapper yourself to ignore the first value.

For example with a function

    function subscribeIgnoreFirst(store, fn) {
        let firedFirst = false;
        return store.subscribe(state => {
            if (!firedFirst) {
                firedFirst = true;
            } else {
                fn(state);
            }
        })
    }

Some other obervations.

  1. A javasript function always returns a value. Even if you don't return a value the function returns undefined.

  2. A store always returns "the current value" when you subscribe. So the store always returns a value when you subscribe. Or do you like to wait for the next change if you are the first subscriber. Or wait forever if you missed the first one. Maybe the next change will never arrive.

  3. Ofcourse it's quite easy to skip the initial value. Or a special initial value.

Related