Search code examples
sveltesveltekitsvelte-3svelte-store

Readable Store, delayed "set"


Is there a way to define a readable store, with its set function, however delay the calling of that function until certain criteria is met?

I'm thinking of using them for API calls, however I want to decide when to call the the set function, which would then fetch the data and populate the store with the results.


Solution

  • The store contract for readable stores is simply a subscribe function; you can arbitrarily extend the store with additional properties and methods. You could e.g. add an update function that internally uses set:

    import { readable } from 'svelte/store';
    
    export function apiStore() {
        const store = readable(null, set => {
            store.update = () => set(new Date());
        });
    
        return store;
    }
    

    Usage:

    <script>
        import { apiStore } from './stores';
        const store = apiStore();
    </script>
    <button on:click={() => store.update()}>Update</button>
    <pre>{$store}</pre>
    

    REPL

    If you want it to update fully automatically, you should use a derived store instead. They update whenever a store they depend upon changes.