Home > Software engineering >  Derived store populated by async request
Derived store populated by async request

Time:09-28

In svelte, I have a store parent:

// parent.js
import { writable } from "svelte/store"

let parent = writable('')

export default parent

I now want to create a derived store child, which fetches additional data from an external API in an asynchronous request. In my views, I would like to await child to be populated with the updated date when I display its contents.

I have worked myself through the examples of stores on svelte.dev, but I was not able to come up with a solution.

I tried to different things, but I feel I lack understanding of how a derived store works in svelte.

CodePudding user response:

You can just call an async function in the derived callback and then await the store content, e.g.

const child = derived(parent, $parent => (async () => {
    // Delay to simulate a long API call
    await new Promise(res => setTimeout(res, 500));
    
    return {
        parent: $parent,
        child: new Date(), // Some new child data here
    };
})()); // <- Immediately invoked async function

(The async function could also be extracted, of course; it would need an argument for the $parent then, as it would no longer form a closure.)

{#await $child then childData}
  ...
{/await}

REPL Example

On every change to the parent store, the child store will call the async function again, returning a new promise.

  • Related