Files
cal.diy/companion/hooks/useUserProfile.ts
T
Dhairyashil ShindeandPeer Richelsen 6650fdb9ef refactor(companion): extract AvailabilityDetailScreen with AppPressable migration (#26106)
* refactor(companion): extract AvailabilityDetailScreen with AppPressable migration

Apply Phases 2, 3, 4 to availability-detail.tsx:
- Phase 2: Extract screen logic (~995 lines) to components/screens/AvailabilityDetailScreen.tsx
- Route file is now a minimal ~35 line wrapper with Stack.Screen config
- Phase 3: ScrollView+map pattern kept (7 days is a fixed small list, FlatList not needed)
- Phase 4: Migrate all TouchableOpacity to AppPressable (63 instances)

Follows the same pattern as EventTypeDetailScreen extraction.

* fix(companion): add GlassView header with Save button to AvailabilityDetailScreen (#26107)

* refactor(companion): extract BookingDetailScreen with AppPressable migration (#26108)

* refactor(companion): extract AvailabilityListScreen with AppPressable migration (#26109)

* fix(companion): add GlassView header with Save button to AvailabilityDetailScreen

* refactor(companion): extract BookingDetailScreen with AppPressable migration

* refactor(companion): extract AvailabilityListScreen with AppPressable migration

* refactor(companion): Standardized error handling with dev-only debug logs (#26110)

* address cubics comments

* address cubics comments

* addressed typecheck erros

* removed localhost from wxt.config for chrome extension

* declare FullScreenModal  FullScreenModalProps

---------

Co-authored-by: Peer Richelsen <[email protected]>

* add loggers for dev env

---------

Co-authored-by: Peer Richelsen <[email protected]>

---------

Co-authored-by: Peer Richelsen <[email protected]>
2025-12-22 22:47:55 +00:00

165 lines
4.2 KiB
TypeScript

/**
* User Profile Query Hooks
*
* This module provides React Query hooks for fetching and updating user profile.
* It integrates with the existing CalComAPIService and provides:
* - Automatic caching with configurable stale times
* - Profile update mutations with cache invalidation
*/
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { CalComAPIService, UserProfile } from "../services/calcom";
import { CACHE_CONFIG, queryKeys } from "../config/cache.config";
/**
* User profile update input type
*/
export interface UpdateUserProfileInput {
email?: string;
name?: string;
timeFormat?: number;
defaultScheduleId?: number;
weekStart?: string;
timeZone?: string;
locale?: string;
avatarUrl?: string;
bio?: string;
metadata?: Record<string, unknown>;
}
/**
* Hook to fetch the current user profile
*
* @returns Query result with user profile data, loading state, error, and refetch function
*
* @example
* ```tsx
* const { data: profile, isLoading } = useUserProfile();
*
* if (profile) {
* console.log(profile.username, profile.email);
* }
* ```
*/
export function useUserProfile() {
return useQuery({
queryKey: queryKeys.userProfile.current(),
queryFn: () => CalComAPIService.getUserProfile(),
staleTime: CACHE_CONFIG.userProfile.staleTime,
// Keep previous data while fetching new data (smoother UX)
placeholderData: (previousData) => previousData,
});
}
/**
* Hook to get the current username
*
* @returns Query result with username
*
* @example
* ```tsx
* const { data: username } = useUsername();
* ```
*/
export function useUsername() {
const { data: profile, ...rest } = useUserProfile();
return {
...rest,
data: profile?.username,
};
}
/**
* Hook to update the user profile
*
* @returns Mutation function and state
*
* @example
* ```tsx
* const { mutate: updateProfile, isPending } = useUpdateUserProfile();
*
* updateProfile({
* name: 'New Name',
* timeZone: 'America/New_York'
* });
* ```
*/
export function useUpdateUserProfile() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (updates: UpdateUserProfileInput) => CalComAPIService.updateUserProfile(updates),
onMutate: async (newData) => {
// Cancel any outgoing refetches
await queryClient.cancelQueries({ queryKey: queryKeys.userProfile.current() });
// Snapshot the previous value
const previousProfile = queryClient.getQueryData<UserProfile>(
queryKeys.userProfile.current()
);
// Optimistically update to the new value
if (previousProfile) {
queryClient.setQueryData(queryKeys.userProfile.current(), {
...previousProfile,
...newData,
});
}
return { previousProfile };
},
onError: (error, _newData, context) => {
// Rollback on error
if (context?.previousProfile) {
queryClient.setQueryData(queryKeys.userProfile.current(), context.previousProfile);
}
console.error("Failed to update user profile");
if (__DEV__) {
const message = error instanceof Error ? error.message : String(error);
const stack = error instanceof Error ? error.stack : undefined;
console.debug("[useUpdateUserProfile] failed", { message, stack });
}
},
onSettled: () => {
// Always refetch after error or success
queryClient.invalidateQueries({ queryKey: queryKeys.userProfile.current() });
},
});
}
/**
* Hook to prefetch user profile (useful for app initialization)
*
* @returns Function to prefetch user profile
*/
export function usePrefetchUserProfile() {
const queryClient = useQueryClient();
return () => {
queryClient.prefetchQuery({
queryKey: queryKeys.userProfile.current(),
queryFn: () => CalComAPIService.getUserProfile(),
staleTime: CACHE_CONFIG.userProfile.staleTime,
});
};
}
/**
* Hook to invalidate user profile cache
*
* @returns Function to invalidate user profile cache
*/
export function useInvalidateUserProfile() {
const queryClient = useQueryClient();
return () => {
queryClient.invalidateQueries({ queryKey: queryKeys.userProfile.all });
};
}
/**
* Type exports for consumers
*/
export type { UserProfile };