Files
cally/hooks/firebase/useUpdateHouseholdName.ts
2025-02-06 22:47:18 +01:00

48 lines
1.5 KiB
TypeScript

import firestore from "@react-native-firebase/firestore";
import { useMutation, useQueryClient } from "@tanstack/react-query";
export const useUpdateHouseholdName = () => {
const queryClient = useQueryClient();
return useMutation({
mutationKey: ["updateHouseholdName"],
mutationFn: async ({
familyId,
name,
}: {
familyId: string;
name: string;
}) => {
try {
// Reference to the Households collection
const householdRef = firestore().collection("Households");
// Query to check if the household exists
const snapshot = await householdRef.where("familyId", "==", familyId).get();
if (!snapshot.empty) {
// If a household with the familyId exists, update the name
const docId = snapshot.docs[0].id;
await householdRef.doc(docId).update({ name });
} else {
// If no household exists, create a new one with familyId and name
console.log("No household found, creating a new one...");
await householdRef.add({ familyId, name });
console.log("New household created successfully.");
}
} catch (e) {
console.error("Error updating or creating household:", e);
throw e; // Ensure error propagates to the mutation error handling
}
},
onSuccess: () => {
queryClient.invalidateQueries({queryKey: ["households"]}); // Invalidate the "households" query to refresh data
},
});
};