Skip to content

Instantly share code, notes, and snippets.

@sibelius
Last active December 26, 2022 07:05
Show Gist options
  • Save sibelius/bd7e865639ddacc7ec38f288e9244d23 to your computer and use it in GitHub Desktop.
Save sibelius/bd7e865639ddacc7ec38f288e9244d23 to your computer and use it in GitHub Desktop.
usePermission react hook to handle frontend authorization concerns

why is this a React hook?

this is a simplified version of the production/real world version

You can consume roles from context/redux/relay or other place to improve dx and void bugs

const App = ({ user }) => {
const { hasRole } = usePermission(user);
return (
<span>Hello</span>
{hasRole('PRODUCT:CREATE') && <button>Create Product</button>
);
}
const usePermission = (user: UserPermission_user) => {
const hasRole = (role: string) => {
return user.roles.includes(role);
};
return {
hasRole
};
};
@guiguetz
Copy link

guiguetz commented Apr 3, 2020

  const hasRole = (role: string) => {
    return user.roles.includes(roles);
  };

shouldn't it be

const hasRole = (role: string) => {
  return user.roles.includes(role);
};

@sibelius
Copy link
Author

sibelius commented Apr 3, 2020

updated, tks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment