'Sveltekit loader while fetching in load function

I have a load function in SvelteKit. It fetches some data.

Is there a way I can display a loader before load function resolves? Or have some SSG that will be updated once SSR is resolved? Anything to make the flow a bit more smooth instead of having no way to return feedback to the user...

<script context="module">
        export const async load = ({ fetch }) => {
            const response = await fetch('https://dog.ceo/api/breeds/image/random')
            return {
                data: await response.json()
            }
        }
</script>

<script>
        export let data;
</script>

<img src={data.message} alt="Dog image" />

I want to have a loader until load is finished or some default data value until load is finished for better user experience. I don't want to move it to onMount, because I want to call an api on SSR.

I'm searching for a combination of initial CSR, until SSR load is done. I want this also to work on initial load and not only when navigating.



Solution 1:[1]

Sure, the simplest way is that you could await the fetching like in the documentation

https://svelte.dev/repl/70e61d6cc91345cdaca2db9b7077a941?version=3.46.4

<script>
    const fetchImage = (async () => {
        const response = await fetch('https://dog.ceo/api/breeds/image/random')
    return await response.json()
    })()
</script>

{#await fetchImage}
    <p>...waiting</p>
{:then data}
    <img src={data.message} alt="Dog image" />
{:catch error}
    <p>An error occurred!</p>
{/await}

Or any alternative such as assigning a reactive variable should work too

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lzadhito