import {where} from "firebase/firestore"; import {useLazyLoadQueryList} from "../../hooks"; import { useAppDispatch } from "../../reduxHooks"; import { Contact, UserData } from "../../typeDefinitions"; import { addContact, deleteContact, updateContact } from "./contactsSlice"; export function useContacts({user}: {user: UserData}){ const dispatch = useAppDispatch() const {items, loadMore, loadMoreIcon, reset} = useLazyLoadQueryList({path: "contacts", constraints: where("uid", "==", user?.id), number: 5}); // const contacts = user?.product === "institutes" && user.userType === "Students" ? // useInstituteStudentSelector((state) => state.contacts) : // user?.product === "students" ? useStudentSelector((state) => state.contacts) : undefined; // const [loadMoreIcon, setLoadMoreIcon] = useState(false); // const firebaseQuery = new FirebaseQuery() // const dispatch = user?.product === "institutes" && user.userType === "Students" ? // useInstituteStudentDispatch() : // user?.product === "students" ? useStudentDispatch() : undefined; // if (!dispatch || !contacts) { // throw new Error("Cannot access featture."); // } // const reset = () => { // dispatch(setContacts({})) // dispatch(setLastContact(undefined)); // }; // const loadMore = async () => { // setLoadMoreIcon(true); // let formattedConstraints:QueryConstraint[] = []; // if (constraints) { // formattedConstraints = (Array.isArray(constraints) ? [...constraints, limit(number)] : [constraints, limit(number)]); // } // if (contacts.lastContact) { // formattedConstraints.push(startAfter(contacts.lastContact)); // } // const documents = await firebaseQuery.getDocsWhere("contacts", formattedConstraints, true) as QuerySnapshot; // const lastContact = documents.docs[documents.docs.length - 1]; // dispatch(setLastContact(lastContact)) // console.log("docs", Object.entries(documents.docs)) // dispatch(setContacts({ // ...contacts, // ...Object.fromEntries( // documents.docs.map(doc => [doc.id, {...doc.data(), docPath: doc.ref}]) // ) // })); // setLoadMoreIcon(false); // }; // useEffect(() => { // loadMore(); // }, []); const addContactForm = async (contactForm: Contact) => { if (!user?.id) return dispatch(addContact({contactForm: contactForm, userId: user.id})) } const updateContactForm = async (contactId: string, attributes: any) => { dispatch(updateContact({contactId: contactId, attributes: attributes})) }; const deleteContactForm = async (contactId: string) => { dispatch(deleteContact({contactId: contactId})) } return ({...{updateContactForm, addContactForm, deleteContactForm, contacts: items, loadMore, loadMoreIcon, reset}}); };