在+SvelteKit中使用ContextApi在+page.server.ts中。

huangapple go评论58阅读模式
英文:

Using ContextApi in SvelteKit in +page.server.ts

问题

我有一个与外部API连接的SvelteKit应用程序。用户打开我的网站后,我从外部API获取用户数据并将其保存在使用ContextAPI包装的store中(参考https://kit.svelte.dev/docs/state-management#using-stores-with-context),但是当我尝试在+page.server.ts中使用getContext('user')时,我收到一个错误:

Error: Function called outside component initialization

我的问题是:如何在+page.server.ts文件的加载函数中访问此数据?

英文:

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.

答案1

得分: 2

存储和上下文适用于页面和组件,您应该或不能在服务器上使用它们。

您可以做的是从 +layout.server.ts 文件中获取数据,通过事件对象的 parent 属性。

export const load: PageServerLoad = async e =>
{
	const layoutData = await e.parent();
    ...

请注意,这通常是不必要的。页面将自动获取合并的布局和页面数据,因此只有在 load 函数本身需要访问时才会真正有用。

英文:

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.

huangapple
  • 本文由 发表于 2023年6月22日 17:55:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76530685.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定