All files / src/hooks use-user-profile.ts

72.72% Statements 8/11
21.05% Branches 4/19
100% Functions 3/3
72.72% Lines 8/11

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 46 47 48 49 50 51 52 53 54 55 56 57                      5x 17x 17x             17x   14x             17x 17x                                     17x              
import { useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useAuthStore } from '@/store/auth-store';
import { useUserStore } from '@/store/user-store';
import { profileService } from '@/features/setting/services/profile.service';
import { formatAvatarUrl } from '@/lib/format-avatar';
 
/**
 * Hook for loading and managing user profile data
 * Use this in components that specifically need profile information
 */
export const useUserProfile = () => {
  const { isAuthenticated, user } = useAuthStore();
  const { setProfile } = useUserStore();
 
  const {
    data: profileData,
    isLoading,
    error,
    refetch,
  } = useQuery({
    queryKey: ['user-profile', user?.id],
    queryFn: () => profileService.getProfile(),
    enabled: isAuthenticated && !!user,
    staleTime: 5 * 60 * 1000, // 5 minutes
    retry: 2,
  });
 
  // Store profile data when loaded
  useEffect(() => {
    Iif (profileData && isAuthenticated) {
      // Use centralized avatar formatting utility
      const avatarUrl = formatAvatarUrl(profileData.avatar);
 
      // Transform API profile data to store format
      const storeProfile = {
        id: profileData.id?.toString() || '',
        name: profileData.name || profileData.username || '',
        email: profileData.email || '',
        phone: profileData.phone || '',
        nationality: profileData.nationality || '',
        username: profileData.username || '',
        avatar: avatarUrl,
      };
 
      setProfile(storeProfile);
    }
  }, [profileData, isAuthenticated, setProfile]);
 
  return {
    profile: profileData,
    isLoading,
    error,
    refetch,
  };
};