38 lines
871 B
TypeScript
Executable file
38 lines
871 B
TypeScript
Executable file
import { useContext } from 'react';
|
|
import { AuthContext } from './AuthProvider';
|
|
import { AuthContextValue } from './types';
|
|
|
|
/**
|
|
* Hook to access authentication context
|
|
* Must be used within an AuthProvider
|
|
*
|
|
* @example
|
|
* ```tsx
|
|
* function MyComponent() {
|
|
* const { user, isAuthenticated, login, logout } = useAuth();
|
|
*
|
|
* if (!isAuthenticated) {
|
|
* return <LoginForm onSubmit={login} />;
|
|
* }
|
|
*
|
|
* return (
|
|
* <div>
|
|
* <p>Welcome, {user.username}!</p>
|
|
* <button onClick={logout}>Logout</button>
|
|
* </div>
|
|
* );
|
|
* }
|
|
* ```
|
|
*/
|
|
export function useAuth(): AuthContextValue {
|
|
const context = useContext(AuthContext);
|
|
|
|
if (context === undefined) {
|
|
throw new Error(
|
|
'useAuth must be used within an AuthProvider. ' +
|
|
'Wrap your app with <AuthProvider> to use authentication.'
|
|
);
|
|
}
|
|
|
|
return context;
|
|
}
|