Files
flyer-crawler.projectium.com/src/hooks/queries/useUserProfileDataQuery.ts
Torben Sorensen dcd9452b8c
All checks were successful
Deploy to Test Environment / deploy-to-test (push) Successful in 13m46s
Adopt TanStack Query
2026-01-10 10:45:10 -08:00

63 lines
2.1 KiB
TypeScript

// 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 profile: UserProfile = await profileRes.json();
const achievements: (UserAchievement & Achievement)[] = await achievementsRes.json();
return {
profile,
achievements: achievements || [],
};
},
enabled,
staleTime: 1000 * 60 * 5, // 5 minutes
});
};