javascriptsveltesvelte-store

Combine contents of svelte store with store of stores


I am trying to create a derived store which concatenates the values of a store with the values of a store of an array of stores

import {writable, derived} from 'svelte/store';

const a = writable(1);
const b = writable([writable(2), writable(3)]);

const combined = derived([a, b], ([$a, $b]) => {

    ?

} 

How can I create a derived store which combines these values so that when I subscribe to the derived store I get an array of all three values:

console.log($combined) = [1, 2, 3]

Solution

  • You can also import get from the svelte/store, it allows you to read the value of a store at an arbitrary point. Use that to map the array of stores to regular variables, and use flat to flatten to array.

    Your code would look something like this

    const combined = derived([a, b], ([$a, $b]) => {
        return [$a, $b.map(b => get(b))].flat()
    }); 
    

    Note that putting stores in stores like this is really bad practice, you will likely not get the reactivity you expect. In this case the derived function will run when either a or b changes, but changes to a store inside of b will not trigger the derived function because b itself didn't change.