Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
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?

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

Definitely possible and described in this page in the documentation.

You just have to make your key (the url of the request in your case) to be falsy when you don't want the request to happen.

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

let { data: roleOneData, error: roleOneError } = useSWR(
    userData?.role === "one" ? "/api/getRoleOneInfo" : null,
    fetcher
  )

let { data: roleTwoData, error: roleTwoError } = useSWR(
    userData?.role === "two" ? "/api/getRoleTwoInfo" : null,
    fetcher
  )
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!