Search code examples
sveltesvelte-store

svelte reactive declaration on store level


In svelte for case where some part's of component state needs to be computed based on others we can use reactive declaration. As official doc stands https://svelte.dev/tutorial/reactive-declarations $: doubled = count * 2. I wonder why it is component level but not store level. Svelte store has no feature like this, right? The one way I see to achieve this is to create custom store, that implements subscribe to satisfy store contract but powered by something else that supports such approach out of the box. Let's say mobx and its computeds. Do I miss something important or there is no other way?


Solution

  • There are derived stores in Svelte, whose value is computed based on one or more other stores
    tutorial - docs - REPL

    import {writable, derived} from 'svelte/store'
    
    export const count = writable(2)
    
    export const doubled = derived(count, $count => $count * 2)