Home > Software engineering >  sveltekit fetch function with ajax requests
sveltekit fetch function with ajax requests

Time:12-09

In my sveltekit app I make AJAX calls to my api endpoints. For example:

page.svelte

<script>
 async function get_card() {
        const url = '/api/card/?category='   $page.params.slug;
        const response = await fetch(url, {
                method: 'GET',
            })
        const card = await response.json();
        return card;
    }
</script>

In the browser javascript console I get this warning:

Loading /api/card/?category=Neurology using `window.fetch`. 
For best results, use the `fetch` that is passed to your `load` 
function: https://kit.svelte.dev/docs/load#making-fetch-requests

But as far as I can tell, that fetch function is only accessible to me on the server, and I do not see a way to use it in a script that may run on the client (such as page.svelte). I tried passing the function as part of the data object from load:

layout.server.js

export const load = async ({ fetch, locals }) => {
    return {
      email: locals.user.email,
      group: locals.user.group,
      fetch: fetch
    }
}

But, not surprisingly, that does not work since the function is not serializable.

Am I Doing It Wrong™, or should I just ignore the warning?

CodePudding user response:

fetch is originally a browser API and SvelteKit defines it on the server as well, if it does not exist. The warning is there to tell you that you are creating another round trip to the server (one for the page and one for the data) when you possibly could have loaded the data on the server so it could be transmitted as part of the page (during server-side rendering).

If the code of your function is not executed right away, then this is a false positive (recent issue on this). I.e. if the data should be requested at a significantly later point, there is no way to bundle the request with the page.

(You are definitely not meant to pass on the fetch of load, you are supposed to use it to get the data.)

  • Related