6

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.

2 Answers 2

3

The loading state to track the load function progress will be implemented after the 1.0 release, hopefully soon, via the introduction of a special route file +loading.svelte see the issue https://github.com/sveltejs/kit/issues/7213 and the response from Rich https://github.com/sveltejs/kit/issues/7213#issuecomment-1318758519

Sign up to request clarification or add additional context in comments.

Comments

-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

4 Comments

I am using sveltekit built-in "load" function for SSR kit.svelte.dev/docs/loading. Imagine you put your fetchImage in it so it happens serverside, but I also want that <p>...waiting</p> until load function resolves. That way I have SSR but also no blank screen. Your example is pure CSR no?
can you provide the code? so I could understand better of the problem :)
afaik SSR wouldn't need any loading state. SSR should return the data if the data is ready. The problem you mention above I assume it occur from other than the load function
I added a comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.