Search code examples
javascripttypescriptqwik

How can I create a non-serializable function in QWIK that avoids automatic serialization?


I need to prevent certain functions from being serialized in QWIK due to accessibility reasons. Serialization of these functions during download leads to unacceptable delays. How can I create these non-serializable functions effectively in QWIK while ensuring they maintain their performance and functionality?

export const ProductFinder = component$(() => {
  const product = useSignal<string>("")
  const nav = useNavigate();
  useStylesScoped$(styles);

  const handleSearch = $(async () => {
    if (product.value.length !== 0) await nav(`/?page=1&categoryType=NEW&filter=${product.value}`);
  })

  return (
    <div class="form">
      <input type="text" class="input" placeholder="Buscar productos" value={product.value} onInput$={(event) => (product.value = (event.target as HTMLInputElement).value)} />
      <button class="button" onClick$={handleSearch} aria-label='Search'>
        <SearchNormalIcon size='100%' />
      </button>
    </div>
  )
});

Solution

  • You can make any value and function non serializable in qwik by providing type NoSerialize and then using function noSerialize().

    import { component$, noSerialize, type NoSerialize, useStore } from '@builder.io/qwik';
    
    type Props = {
      someMethod: NoSerialize<() => void>;
    }
    export const ProductFinder = component$(({someMethod}:Props) => {
      const product = useSignal<string>("")
      const someObj = useSignal<NoSerialize<any>>()
      const nav = useNavigate();
      useStylesScoped$(styles);
    
      const handleSearch = $(async () => {
        noSerialize(() => console.log("some log"));
        someObj.value = noSerialize(some value)
        if (product.value.length !== 0) await nav(`/?page=1&categoryType=NEW&filter=${product.value}`);
      })
    
      return (
        <div class="form">
          <input type="text" class="input" placeholder="Buscar productos" value={product.value} onInput$={(event) => (product.value = (event.target as HTMLInputElement).value)} />
          <button class="button" onClick$={handleSearch} aria-label='Search'>
            <SearchNormalIcon size='100%' />
          </button>
        </div>
      )
    });