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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | 1x 1x 1x 1x | import { useCallback, useEffect, useState } from 'react';
import type { EarnedBadge, PublicProfile } from '@/models/profile';
import { profileService } from '@/services/profileService';
import i18n from '@/i18n';
export function usePublicProfileViewModel(
userId: string | undefined,
authToken: string | null | undefined,
) {
const [profile, setProfile] = useState<PublicProfile | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [earnedBadges, setEarnedBadges] = useState<EarnedBadge[]>([]);
const [earnedBadgesLoading, setEarnedBadgesLoading] = useState(false);
const [earnedBadgesError, setEarnedBadgesError] = useState<string | null>(null);
const fetchProfile = useCallback(async () => {
if (!userId) {
setProfile(null);
setError(i18n.t('errors.public_profile_user_id_missing'));
setIsLoading(false);
return;
}
setIsLoading(true);
setError(null);
try {
const data = await profileService.getPublicProfile(userId);
setProfile(data);
} catch (err: unknown) {
setProfile(null);
setError(err instanceof Error ? err.message : i18n.t('errors.public_profile_load_failed'));
} finally {
setIsLoading(false);
}
}, [userId]);
useEffect(() => {
void fetchProfile();
}, [fetchProfile]);
const fetchEarnedBadges = useCallback(async () => {
if (!userId || !authToken) {
setEarnedBadges([]);
setEarnedBadgesError(null);
setEarnedBadgesLoading(false);
return;
}
setEarnedBadgesLoading(true);
setEarnedBadgesError(null);
try {
const res = await profileService.getUserBadges(userId, authToken);
setEarnedBadges(res.items ?? []);
} catch (err: unknown) {
setEarnedBadges([]);
setEarnedBadgesError(
err instanceof Error ? err.message : i18n.t('errors.profile_badges_failed'),
);
} finally {
setEarnedBadgesLoading(false);
}
}, [userId, authToken]);
useEffect(() => {
void fetchEarnedBadges();
}, [fetchEarnedBadges]);
return {
profile,
isLoading,
error,
retry: fetchProfile,
earnedBadges,
earnedBadgesLoading,
earnedBadgesError,
refreshEarnedBadges: fetchEarnedBadges,
};
}
|