简体   繁体   中英

How do i pass a function from remix loader function?

I am trying to send a function as one of the value from a remix route loader function

export const loader: LoaderFunction = async ({ request }) => {
  const userId = await requireUserId(request)
  const user = await getUserById(userId)

  const canUserPerformAction = getUserPermissions(user)

  const organisations = await Organisation.find({}).exec()
  return {
      organisations,
      canUserPerformAction
  }
}

getUserPermissions(user) returns a function with the current user context, which needs to be used in the frontend.

this function always ends up being undefined when I fetch it using useLoaderData() in the default component/ frontend. Is there a better way to do this?

Your loader can either be called during the whole page generation, or using an XHR when navigating in your app.

Your loader have to return a valid Response object, which will usually be a JSON response : https://remix.run/docs/en/v1/api/conventions#returning-response-instances

In your code sample, the returned object is automatically converted to a JSON string, and since functions aren't valid json, it gets stripped.

You will need to call your canUserPerformAction and return its actual result as JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM