I recently discovered the handleFetch
hook in Sveltekit. Now I'm trying to use it to intercept calls to my backend (written in Go) but doesn't seem to work (unless I'm missing something).
The documentation reads:
This function allows you to modify (or replace) a fetch request that happens inside a load or action function that runs on the server (or during pre-rendering).
I've got src\hooks.server.js
:
/** @type {import('@sveltejs/kit').HandleFetch} */
export async function handleFetch({ request, fetch }) {
console.log("HERE IN --------> HANDLE FETCH HOOK")
return fetch(request);
}
As you can see I'm just trying to make sure the hooks is called by printing a message on the terminal.
I've got a load
function in src\routes\records\+page.server.js
:
export async function load() {
console.log("HERE IN LOAD")
// const records = await getAllRecords(1, 10);
const response = await fetch(`http://127.0.0.1:8080/api/v1/records?page=1&per_page=2`);
const records = await response.json();
console.log(await records);
return records;
}
Although I see the HERE IN LOAD
message and the response being printed I never see the message that indicates that the hook was hit.
What am I missing?
Thanks
You need to use the fetch
function that is provided to the load
function as a prop.
export async function load({ fetch }) { // destructure `fetch` from the first argument
console.log("HERE IN LOAD")
// const records = await getAllRecords(1, 10);
const response = await fetch(`http://127.0.0.1:8080/api/v1/records?page=1&per_page=2`);
const records = await response.json();
console.log(await records);
return records;
}
You can read more about which props are passed to load
functions here.