无法从 npm 库导入序列化值

Value cannot be serialized from npm library import

提问人:janat08 提问时间:9/16/2023 更新时间:9/16/2023 访问量:57

问:

  import { createClient } from '@propelauth/javascript'
  const store = useStore({client: null, loggedIn: null})
  useVisibleTask$(async (ctxt) => {
    store.client =  await createClient({ authUrl: 'https://91205364487.propelauthtest.com' })
    store.loggedIn = store.client.getAuthenticationInfoOrNull(true)
})

导致错误:错误:无法在 _.addLoggedInChangeObserver 中序列化值,因为它是名为“addLoggedInChangeObserver”的函数。您可能需要使用 $(fn) 将其转换为 QRL: const addLoggedInChangeObserver = $(addLoggedInChangeObserver(loggedInChangeObserver) { const hasObserver = clientState.observers.includes(loggedInChangeObserver); if (hasObserver) { console.error(“Observer has been attached already.”); else if (!loggedInChangeObserver) { console.error(“无法添加空观察者”); else { clientState.observers.push(loggedInChangeObserver);请查看 https://qwik.builder.io/docs/advanced/qrl/ 了解更多信息。

qwik qwikjs

评论


答:

1赞 Harsh Mangalam 9/16/2023 #1

存储必须始终可序列化,但如果要在存储中存储不可序列化的属性,则可以使用函数,当应用程序暂停时,该属性将在服务器上丢弃,并且仅在浏览器中可用。noSerialize()

Qwik 文档 https://qwik.builder.io/tutorial/store/no-serialize/


import {
  component$,
  useStore,
  type NoSerialize,
  useVisibleTask$,
  noSerialize,
} from "@builder.io/qwik";
import {
  type IAuthClient,
  createClient,
  type AuthenticationInfo,
} from "@propelauth/javascript";

type Store = {
  client: NoSerialize<IAuthClient> | null;
  loggedIn: NoSerialize<AuthenticationInfo> | null;
};
export default component$(() => {
  const store = useStore<Store>({ client: null, loggedIn: null });
  useVisibleTask$(async () => {
    const client = await createClient({
      authUrl: "https://91205364487.propelauthtest.com",
    });
    const loggedIn = await client.getAuthenticationInfoOrNull(true);
    store.client = noSerialize(client);
    if (loggedIn) {
      store.loggedIn = noSerialize(loggedIn);
    }
  });
  return <pre>{JSON.stringify(store, null, 4)}</pre>;
});