Svelte store subscribed function should not be invoked on subscription
Asked Answered
H

2

5

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?

Horsa answered 26/3, 2021 at 14:22 Comment(0)
S
7

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);
            }
        })
    }
Shalondashalt answered 26/3, 2021 at 14:58 Comment(1)
Thanks very much! So that's intended behaviour. I hate it when my intuition leads me down the wrong path.Horsa
F
1

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.

Fence answered 26/3, 2021 at 17:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.