bw-expo-app/hooks/use-auth-guard.ts

41 lines
955 B
TypeScript

import { useContext } from 'react';
import { AuthContext, type AuthContextType } from '@/components/auth/auth-provider';
/**
* Hook for auth protection
* 提供认证拦截功能,当需要登录时自动弹出登录模态框
*
* @returns Object with requireAuth function
*
* @example
* ```typescript
* function MyComponent() {
* const { requireAuth } = useAuthGuard();
*
* const handleProtectedAction = () => {
* const canProceed = requireAuth(() => {
* // 执行需要登录的操作
* doSomething();
* });
*
* if (!canProceed) {
* // 登录模态框会自动弹出
* return;
* }
*
* // 已登录,直接执行
* doSomething();
* };
* }
* ```
*/
export function useAuthGuard(): AuthContextType {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuthGuard must be used within an AuthProvider');
}
return context;
}