0

The documentation in just says to create a +page.ts file of

import type { PageLoad } from './$types';

export const load: PageLoad = async ({ fetch, params }) => {
    const res = await fetch(`/api/items/${params.id}`);
    const item = await res.json();

    return { item };
};

but it doesn't include any form of error handling. In vanilla JS, I will have to throw and catch with fetch, but in Svelte I am unable to find the necessary syntax and similar information.

3
  • This is regular TS, try/catch? Or where and how do you intend to handle the error? Commented May 6 at 15:00
  • I plan on handling the error in the client side. When I receive some kind of an error, I will show a toast msg saying "{error} pls try again" Commented May 6 at 15:24
  • I guess you're the guy from Reddit. Don't throw on non-OK responses. This is something axios, ky and similar packages have perpetuated and is a bad thing to do. Since you are using TypeScript, use dr-fetch (my creation), the only fetch wrapper in the world that can type the response body according to the HTTP response that it receives. Commented May 6 at 15:33

1 Answer 1

0

I think your answer is to stream your fetches instead of awaiting them in the load function, as per the documentation:

[....] you can return a nested promise from a server load function, and SvelteKit will start rendering the page before it resolves. Once it completes, the result will be streamed to the page.

You could do something like this:

import type { PageLoad } from './$types';

export const load: PageLoad = async ({ fetch, params }) => {

    const fetchItem = fetch(`/api/items/${params.id}`)

    return { 
        streamed: {
            item: fetchItem();
        };
    };

});

And handle the promise in your +page.svelte using a try/catch or the #await block from Svelte. Hope this helps!

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

1 Comment

The whole "nested promise" thing is outdated. SvelteKit 2 no longer awaits anything.

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.