SolidJSS
SolidJSโ€ข2y agoโ€ข
7 replies
hannus

Confusion about Preload mechanism

I am confused about the preload mechanism. According to my understanding, adding an asynchronous function wrapped by a cache in preload initiates data fetching when the route is accessed, ensuring the data is ready when the page starts rendering. Observing the console, this indeed happens. When the function is called within the route component, the data should already be prepared. Even if an asynchronous function calls this function, it should immediately return the data. However, my observation is different; there is still an asynchronous process to re-fetch the data.

The sample code is as follows:
// function in the preload()
export async function handleUser(): Promise<void> {
  "use server";
  const userinfo = await fetchUserInfo("http://localhost:8000/getuserinfo/");  
  console.log("userinfo", userinfo);
  if (userinfo === undefined) {
    throw redirect("/login")
  }
}

export const handleUserCache = cache(handleUser, "handleUser");

// in route component file

export const route = {
  preload() {
    handleUserCache();
  }
} satisfies RouteDefinition;

export default function Auth() {
  console.log("start auth page render")
  const userinfo = createAsync(() => handleUserCache());
    console.log("after async function")

return ....
Was this page helpful?