Files
cally/hooks/useFetchAndSaveGoogleEvents.ts
Milan Paunovic c411990312 Fixes
2024-12-15 16:46:26 +01:00

38 lines
1.3 KiB
TypeScript

import {useMutation, useQueryClient} from "@tanstack/react-query";
import {useAuthContext} from "@/contexts/AuthContext";
import functions from "@react-native-firebase/functions";
interface SyncResponse {
success: boolean;
eventCount: number;
message?: string;
}
export const useFetchAndSaveGoogleEvents = () => {
const queryClient = useQueryClient();
const { profileData } = useAuthContext();
return useMutation({
mutationKey: ["fetchAndSaveGoogleEvents", "sync"],
mutationFn: async ({ email }: { email?: string }) => {
if (!email || !profileData?.googleAccounts?.[email]) {
throw new Error("No valid Google account found");
}
try {
const response = await functions()
.httpsCallable('triggerGoogleSync')({ email });
return response.data as SyncResponse;
} catch (error: any) {
console.error("Error initiating Google Calendar sync:", error);
throw new Error(error.details?.message || error.message || "Failed to sync calendar");
}
},
onSuccess: (data) => {
queryClient.invalidateQueries({queryKey: ["events"]});
console.log(`Successfully synced ${data.eventCount} events`);
}
});
};