Created
February 19, 2021 08:40
-
-
Save rockiger/cca24615b062f01eccdba6fd8ebff262 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
// Auth.js | |
const AuthContext = createContext({username: '', role: ''}); | |
export function useAuth() { | |
const context = useContext(AuthContext); | |
if (!context) { | |
throw new Error('useAuth must be used within a AuthProvider'); | |
} | |
return context; | |
} | |
export function AuthProvider({ children }) { | |
const [user, setUser] = useState({username: '', role: ''}); | |
return ( | |
<AuthContext.Provider value={{ user }}> | |
{children} | |
</AuthContext.Provider> | |
); | |
} | |
// App.js | |
export function App() { | |
return ( | |
<AuthProvider> | |
<Component /> | |
</AuthProvider> | |
); | |
} | |
// Component.js | |
export function Component() { | |
const { user } = useAuth() | |
if (user?.role === 'ADMIN') { | |
return <AdminView /> | |
} else { | |
return <UserView /> | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment