added household name

This commit is contained in:
ivic00
2024-11-17 23:53:28 +01:00
parent c1f7113dfc
commit 111244e178
7 changed files with 204 additions and 37 deletions
+36
View File
@@ -0,0 +1,36 @@
import { useQuery } from "react-query";
import firestore from "@react-native-firebase/firestore";
export const useGetHouseholdName = (familyId: string) => {
return useQuery(
["getHouseholdName", familyId], // Unique query key
async () => {
console.log(`Fetching household name for familyId: ${familyId}`);
try {
// Query the Households collection for the given familyId
const snapshot = await firestore()
.collection("Households")
.where("familyId", "==", familyId)
.get();
if (!snapshot.empty) {
// Extract the name from the first matching document
const householdData = snapshot.docs[0].data();
console.log("Household found:", householdData);
return householdData.name || null; // Return the name or null if missing
} else {
console.log("No household found for the given familyId.");
return null; // Return null if no household found
}
} catch (e) {
console.error("Error fetching household name:", e);
throw e; // Ensure error propagates to the query error handling
}
},
{
enabled: !!familyId, // Only fetch if familyId is provided
staleTime: 5 * 60 * 1000, // Cache the data for 5 minutes
}
);
};
+50
View File
@@ -0,0 +1,50 @@
import firestore from "@react-native-firebase/firestore";
import { useMutation, useQueryClient } from "react-query";
export const useUpdateHouseholdName = () => {
const queryClient = useQueryClient();
return useMutation({
mutationKey: ["updateHouseholdName"],
mutationFn: async ({
familyId,
name,
}: {
familyId: string;
name: string;
}) => {
console.log("Mutation function called with data:", { familyId, name });
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;
console.log(`Household found with ID ${docId}, updating name...`);
await householdRef.doc(docId).update({ name });
console.log("Household name updated successfully.");
} 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("households"); // Invalidate the "households" query to refresh data
},
});
};