I have a SvelteKit
application connected to external API. After user opens my website I fetch user data from external API and save it in store wrapped in ContextAPI
(based on https://kit.svelte.dev/docs/state-management#using-stores-with-context) but
when i try to use getContext('user')
in +page.server.ts I'm getting an error:
Error: Function called outside component initialization
My question is: How can I get access to this data on load function in +page.server.ts
file.
Stores and contexts are for pages and components, you should or cannot use them on the server.
What you can do, is get data from a +layout.server.ts
file, via the event object's parent
.
export const load: PageServerLoad = async e =>
{
const layoutData = await e.parent();
...
Note that this is generally not necessary. The page will get merged layout and page data automatically, so this really is only useful if the load
function itself needs access.