Search code examples
svelte

Is it possible to #await with onMount together


I'd like to use convenient #await Svelte helper when loading data with fetch().

However, I noticed a warning at onMount tutorial [1]:

It's recommended to put the fetch in onMount rather than at the top level of the <script> because of server-side rendering (SSR).

I don't need SSR, but wanted to try it out. Hovewer, onMount() doesn't return a Promise, and I cannot create a Promise that resolves with onMount().

Is it possible to use onMount() together with #await?

[1] https://svelte.dev/tutorial/onmount


Solution

  • You can declare the promise at the top level and assign it in onMount, to initially show it as loading, it can be initialized to a Promise that does not resolve. E.g.

    let promise = new Promise(() => {});
    
    onMount(() => {
        promise = (async () => {
          const response = await fetch(...);
          // ...
          return data; 
        })();
    });