Best practice for using svetch
within load functions
#7
-
First off, thanks for the lib and your previous technical support. I am looking at how to more smoothly integrate the
But in this example, the fetch passed into |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I'm happy that you're using it! Thank you :) The one where you put a load function into it is for server-side, because if you fetch without passing it on backend, then relative urls + sveltekit optimizations won't apply. The pattern I use is this (you can externalize this in a separate file for verbosity: //+layout.svelte
import { Svetch } from 'svetch.ts'
const svetch = new Svetch(...)
setContext("svetch", svetch) Then in child routes import type { Svetch } from 'svetch.ts'
const svetch = getContext<Svetch>("svetch") you can make this faster, in a separate file import { hasContext, getContext, setContext } from "svelte";
import { Svetch } from "svetch.ts";
export function setSvetchContext(instance: Svetch, key: string = "svetch") {
setContext(key, instance);
}
export function useSvetch(key: string = "svetch") {
if (!hasContext(key)) {
throw new Error("You have not used setSvetchContext in the parent context");
}
return getContext<Svetch>(key);
} Note that when you make a response, there is the res.isOk() type guard which helps you get the data if the response is ok, and res.okOrThrow() which will directly return the typed data or throw. |
Beta Was this translation helpful? Give feedback.
I'm happy that you're using it! Thank you :)
The one where you put a load function into it is for server-side, because if you fetch without passing it on backend, then relative urls + sveltekit optimizations won't apply.
The pattern I use is this (you can externalize this in a separate file for verbosity:
Then in child routes
you can make this faster, in a separate file