'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?
Solution 1:[1]
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
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | n1xx1 |
