SolidJSS
SolidJS12mo ago
13 replies
rtzrtz.

behaviour of createAsync in hooks - why cached?

I'm trying to get a better understanding on createAsync & query, and weather or not it is an appropriate way to share state.
I created a hook and use it like this.

This works perfectly fine. But I'm confused why the logs appear in the console, but no requests are made. I understood, that the query() cashes for only 5 seconds - so why is it not making requests all the timem even on navigation? I can import the hook and access the data from everywhere simultaneously.

Honestly this is the behaviour i hoped for (its easy to revalidate the cash), but I'd like to fully understand why this works.

Thanks!

//useMyHook.tsx
const getData = query(async () => {
  "use server";
  return { user: 1 };
}, "data");

export function useMyHook() {
  const res = createAsync(() => getData());
  return {
    user: () => {
      console.log("I'm am called and logged all the time!")
      return res()?.user,
    }
  };
}

// someComponent.tsx
export default function Page() {
  const { user } = useMyHook();
  return <div>{user()}</div>
}


❤️
Was this page helpful?