roles control on actions

Hi all, I am trying to RBAC actions in a page. I have an array of roles as string for each user. I have a custom hook to check roles:
export default function useCustomRoles(role: string) {
const [ hasRole, setHasRole ] = useState(false)

useEffect(() => {
async function getRoles() {
const res = await http<RolesResonseObject>(`${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/roles`)
setHasRole(res.roles.includes(role))
}

void getRoles();
}, [role]);

return { hasRole }
}
export default function useCustomRoles(role: string) {
const [ hasRole, setHasRole ] = useState(false)

useEffect(() => {
async function getRoles() {
const res = await http<RolesResonseObject>(`${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/roles`)
setHasRole(res.roles.includes(role))
}

void getRoles();
}, [role]);

return { hasRole }
}
I am then using the hook to conditonally render buttons, etc in the UI:
const { hasRole: hasCreatePermission} = useCustomRoles("some-role-here")
const { hasRole: hasCreatePermission} = useCustomRoles("some-role-here")
Does this seem like a good implementation, is there a better way to do it?
2 Replies
Matvey
Matvey14mo ago
If you call this hook multiple times, it will make multiple http requests. You should probably cache the list of roles after the first request Also if you use /app it will be better to get the roles in a server component
ali.mcgill
ali.mcgillOP14mo ago
Thanks that's a good point. 👍
Want results from more Discord servers?
Add your server