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 | 1x | // src/hooks/queries/useUserProfileDataQuery.ts
import { useQuery } from '@tanstack/react-query';
import { getAuthenticatedUserProfile, getUserAchievements } from '../../services/apiClient';
import { queryKeys } from '../../config/queryKeys';
import type { UserProfile, Achievement, UserAchievement } from '../../types';
interface UserProfileData {
profile: UserProfile;
achievements: (UserAchievement & Achievement)[];
}
/**
* Query hook for fetching the authenticated user's profile and achievements.
*
* This combines two API calls (profile + achievements) into a single query
* for efficient fetching and caching.
*
* @param enabled - Whether the query should run (default: true)
* @returns TanStack Query result with UserProfileData
*
* @example
* ```tsx
* const { data, isLoading, error } = useUserProfileDataQuery();
* const profile = data?.profile;
* const achievements = data?.achievements ?? [];
* ```
*/
export const useUserProfileDataQuery = (enabled: boolean = true) => {
return useQuery({
queryKey: queryKeys.userProfileData(),
queryFn: async (): Promise<UserProfileData> => {
const [profileRes, achievementsRes] = await Promise.all([
getAuthenticatedUserProfile(),
getUserAchievements(),
]);
if (!profileRes.ok) {
const error = await profileRes.json().catch(() => ({
message: `Request failed with status ${profileRes.status}`,
}));
throw new Error(error.message || 'Failed to fetch user profile');
}
if (!achievementsRes.ok) {
const error = await achievementsRes.json().catch(() => ({
message: `Request failed with status ${achievementsRes.status}`,
}));
throw new Error(error.message || 'Failed to fetch user achievements');
}
const profileJson = await profileRes.json();
const achievementsJson = await achievementsRes.json();
// API returns { success: true, data: {...} }, extract the data
const profile: UserProfile = profileJson.data ?? profileJson;
const achievements: (UserAchievement & Achievement)[] =
achievementsJson.data ?? achievementsJson;
return {
profile,
achievements: achievements || [],
};
},
enabled,
staleTime: 1000 * 60 * 5, // 5 minutes
});
};
|