Last active
September 4, 2019 13:44
-
-
Save SebastianHGonzalez/416d5fa5c5ce14a3ae6609155c659cfb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createContext } from "react"; | |
const SessionContext = createContext(); | |
export function SessionProvider({ session, children }) { | |
return ( | |
<SessionContext.Provider value={session}> | |
{children} | |
</SessionContext.Provider> | |
); | |
} | |
export const SessionConsumer = SessionContext.Consumer; | |
export default SessionContext; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import useSession from "./useSession"; | |
import { useEffect } from "react"; | |
/** | |
* | |
* @param {string | string[]} permissions required permissions | |
* @param {function} effect called on permission change | |
* @returns {boolean} | |
*/ | |
export default function usePermission(permissions = [], effect = noop) { | |
const session = useSession(); | |
const sessionPermissions = (session && session.permissions) || []; | |
const requiredPermissions = [permissions].flat().filter(i => i); | |
const hasPermission = requiredPermissions.reduce( | |
(res, permission) => res && sessionPermissions.includes(permission), | |
true | |
); | |
useEffect(() => effect(hasPermission), [hasPermission]); | |
return hasPermission; | |
} | |
function noop() {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useContext } from "react"; | |
import Session from "contexts/Session"; | |
export default function useSession() { | |
return useContext(Session); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment