useAuth
useAuthフックは、ユーザーオブジェクトや読み込みステータスなど、現在の認証状態へのアクセスを提供します。
基本的な使い方
import { useAuth } from 'authsafe-react';
function UserProfile() {
const { user, isAuthenticated, isLoading } = useAuth();
if (isLoading) return <div>Loading...</div>;
if (!isAuthenticated) return <div>Please log in</div>;
return (
<div>
<h2>Welcome, {user?.name}!</h2>
<p>Email: {user?.email}</p>
</div>
);
}戻り値
| 財産 | タイプ | 説明 |
|---|---|---|
user | User | null | 現在のユーザーオブジェクト(認証されていない場合はnull) |
isAuthenticated | boolean | ユーザーが現在認証されているかどうか |
isLoading | boolean | 認証状態が読み込まれているかどうか |
error | Error | null | 認証エラーが発生した場合 |
ユーザーオブジェクトプロパティ
| 財産 | タイプ | 説明 |
|---|---|---|
sub | string | 固有のユーザー識別子 |
name | string | ユーザーの表示名 |
email | string | ユーザーのメールアドレス |
picture | string | undefined | ユーザーのプロフィール写真へのURL |
email_verified | boolean | undefined | メールアドレスが認証されているかどうか |
ルートの保護
認証ステータスに基づいてコンテンツを条件付きでレンダリングするには、フックを使用します。
import { useAuth } from 'authsafe-react';
import { Navigate } from 'react-router-dom';
function ProtectedRoute({ children }) {
const { isAuthenticated, isLoading } = useAuth();
if (isLoading) return <div>Loading...</div>;
if (!isAuthenticated) return <Navigate to="/login" />;
return children;
}型定義
export interface User {
sub: string;
name?: string;
email?: string;
picture?: string;
email_verified?: boolean;
[key: string]: any;
}
export interface IUseAuth {
user: User | null;
isAuthenticated: boolean;
isLoading: boolean;
error: Error | null;
}