Thursday, 14 April 2022

Is it possible to call an API based on user roles with useSWR?

I'm wondering if it is possible to use useSWR from Vercel if a condition is true? I.e., if RoleOne is true, then call:

let { data: roleOneData, error: roleOneError } = useSWR(
    "/api/getRoleOneInfo",
    fetcher
  )

My Next.js app is dealing with different user roles, and all user roles are sharing the same Application Shell, which means I call all user role specific API's in the Application Shell. I would like to only call the API I need if it can see a specific user role is true. I'm getting the roles from the userData API.

Here are my fetchers which are used in various functions:

let { data: userData, error: userError } = useSWR("/api/getUserInfo", fetcher)

let { data: roleOneData, error: roleOneError } = useSWR(
    "/api/getRoleOneInfo",
    fetcher
  )

let { data: roleTwoData, error: roleTwoError } = useSWR(
    "/api/getRoleTwoInfo",
    fetcher
  )

If I'm logging in as RoleOne, I'm getting API errors for getRoleTwoInfo and vice versa. I would like to avoid calling RoleTwo API if I'm logged in as RoleOne and the other way around. How can I accomplish that?



from Is it possible to call an API based on user roles with useSWR?

No comments:

Post a Comment