Skip to content

Instantly share code, notes, and snippets.

@rockiger
Created February 19, 2021 08:40
Show Gist options
  • Save rockiger/cca24615b062f01eccdba6fd8ebff262 to your computer and use it in GitHub Desktop.
Save rockiger/cca24615b062f01eccdba6fd8ebff262 to your computer and use it in GitHub Desktop.
// 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