sveltesvelte-store

Adding a readable store to writable store


I'm trying to add a readable store as a default value to a writable store, so that the user will see some default value when he opens the app.

I have one large readable store - taskStore, which contains different objects with task information, as follows:

import { writable, readable } from "svelte/store";

// The video directories together with the corresponding frame counts should be placed here
export const taskStore = readable(
    [ 
        {
            imageDir: '100159',
            frameCount: 50,
            labels: [
                { frame: 10, x: 125, y: 60 },
                { frame: 10, x: 125, y: 60 },
                { frame: 10, x: 125, y: 60 },
            ]
        },
        {
            imageDir: '100589', 
            frameCount: 50, 
            labels: []
        }
    ]
)


So I tried adding the first value of the taskStore to the writable currentTaskStore, like this:

export const currentTaskStore = writable([taskStore[0]])

but it doesn't work, and I get the undefined value when I try to use this store in other components. Is it possible to use a writable store with complicated objects, or are they for primitives only?


Solution

  • Outside of components you can only access the value of stores via subscribe or the get helper function (from svelte/store), which just creates a temporary subscription.

    So if you do get(taskStore)[0], this should work.
    Stores can hold any kind of object.