import { useState } from "react"; import firestore from "@react-native-firebase/firestore"; import { ChildProfile } from "./types/profileTypes"; const useChildren = (user: any) => { const [children, setChildren] = useState([]); const [child, setChild] = useState({ name: "", birthday: new Date(), userType: "child", parentId: "", }); const fetchChildren = async () => { if (user) { const childrenProfiles = await getChildrenByParentId(user.uid); setChildren(childrenProfiles); } }; const getChildrenByParentId = async ( parentId: string ): Promise => { try { const snapshot = await firestore() .collection("Profiles") .where("userType", "==", "child") .where("parentId", "==", parentId) .get(); const children: ChildProfile[] = snapshot.docs.map((doc) => { const data = doc.data(); return { ...data, birthday: data.birthday.toDate(), } as ChildProfile; }); return children; } catch (error) { console.error("Error retrieving child users:", error); return []; } }; const handleNewChild = async (newChild: ChildProfile) => { try { if (user) newChild.parentId = user.uid; await firestore().collection("Profiles").add(newChild); } catch (error) { console.error(error); } finally { setChild((prev) => ({ ...prev, name: "" })); fetchChildren(); } }; return { children, child, setChild, fetchChildren, handleNewChild, }; }; export default useChildren;