All files / app/(tabs)/profile/hooks useProfileData.ts

90.9% Statements 20/22
66.66% Branches 4/6
88.88% Functions 8/9
93.33% Lines 14/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45                      4x 4x 4x 4x 4x   4x     4x 4x 4x 1x 1x             4x 1x     4x                  
import { useEffect } from 'react';
import { useRouter } from 'expo-router';
 
import { useUserStore } from '@/src/store/userStore';
 
/**
 * Profile 数据管理 Hook
 * 负责用户数据的获取和认证状态管理
 */
export function useProfileData() {
  // 使用 userStore - 使用选择器避免不必要的重渲染
  const user = useUserStore((state) => state.user);
  const isLoading = useUserStore((state) => state.isLoading);
  const fetchCurrentUser = useUserStore((state) => state.fetchCurrentUser);
  const isAuthenticated = useUserStore((state) => state.isAuthenticated);
  const _hasHydrated = useUserStore((state) => state._hasHydrated);
 
  const router = useRouter();
 
  // 加载用户数据
  useEffect(() => {
    Iif (!_hasHydrated) return;
    if (!isAuthenticated) return;
    Eif (!user) {
      fetchCurrentUser().catch((e) => {
        console.warn('获取用户信息失败', e);
      });
    }
  }, [user, fetchCurrentUser, isAuthenticated, _hasHydrated]);
 
  // 处理未认证状态
  const handleUnauthenticated = () => {
    router.replace('/login');
  };
 
  return {
    user,
    isLoading,
    isAuthenticated,
    _hasHydrated,
    fetchCurrentUser,
    handleUnauthenticated,
  };
}