I'm working with react and Firebase, and I made an app for Kindergarten. Now, I have some components that shouldn't be visible for the parents. Is there a simple way to do this ? This is my first app ever, especially with Firebase and react.
I was thinking something like checking the role and then just a simple if else statement. I'm not sure if that's a good logic.
CodePudding user response:
Simple if else
statement or switch
block you can use to check for roles but as application starts growing it will be a tedious task to manage all the roles-based logic. It all deals with how you set up your architecture to handle the role
based flow.
I've also encountered a similar flow.
What you can do is create hooks, like useHasRoles
and useUser
.
useHasRoles
hook will check whether your current logged in user has specified role or not. And to get the current user details, we are having another hook as useUser
which will return the current user details and roles of that specific user.
useHasRoles (hook)
const useHasRoles =(roleNames)=>{
const roles = useUser();
if (typeof roleNames === "string") {
//check whether current user has specific role or not
//return true/false
} else if (Array.isArray(roleNames)) {
//check if current user has all roles specified in roleNames
//return true/false
} else {
return false;
}
}
useUser (hook)
const useUser = ()=>{
//get current user details and roles.
return {roles:[]}
}
How to use?
const sample = ()=>{
const hasAdminRole = useHasRoles('ADMIN') // ['ADMIN', 'SUPERADMIN']
// you can pass roles as array, so it will check for all the roles.
}
Let me know if that helps.
CodePudding user response:
There are many ways to do this.
Here is a simple TextButton which is disabled if the user is a parent:
interface Props {
onPress: () => void
children: string
userRole: UserRole
}
const TextButton = ({ onPress, children, userRole }: Props) => {
const disabled = userRole === UserRole.Parent
return (
<TouchableOpacity
activeOpacity={1}
style={styles.button}
onPress={onPress}
disabled={disabled}>
<Text
style={styles.text}
{children}
</Text>
</TouchableOpacity>
)
}