qwikqwikjs

Value cannot be serialized from npm library import


  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)
})

Results in an error: Error: Value cannot be serialized in _.addLoggedInChangeObserver, because it's a function named "addLoggedInChangeObserver". You might need to convert it to a QRL using $(fn): const addLoggedInChangeObserver = $(addLoggedInChangeObserver(loggedInChangeObserver) { const hasObserver = clientState.observers.includes(loggedInChangeObserver); if (hasObserver) { console.error("Observer has been attached already."); } else if (!loggedInChangeObserver) { console.error("Cannot add a null observer"); } else { clientState.observers.push(loggedInChangeObserver); } }); Please check out https://qwik.builder.io/docs/advanced/qrl/ for more information.


Solution

  • Store must always serializable but if you want to store non serializable property inside store you can use noSerialize() function and that property will be discarded on server when application is paused and only available in your browser.

    Qwik docs 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>;
    });