Files
cally/hooks/firebase/useChildren.ts
2024-08-09 19:38:46 +02:00

68 lines
1.6 KiB
TypeScript

import { useState } from "react";
import firestore from "@react-native-firebase/firestore";
import { ChildProfile } from "./types/profileTypes";
const useChildren = (user: any) => {
const [children, setChildren] = useState<ChildProfile[]>([]);
const [child, setChild] = useState<ChildProfile>({
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<ChildProfile[]> => {
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;