From 9e4e06f5c1cafc6c3373fc309420bd6e7032cdea Mon Sep 17 00:00:00 2001 From: ZL Asica <40444637+ZL-Asica@users.noreply.github.com> Date: Thu, 21 Nov 2024 10:53:16 -0600 Subject: [PATCH] refactor(savedOrgs): clean up codes - Remove extra `SavedContext` and corresponde `useSaved` hook. - Create `useSavedOrgs` hook to directly use `UserContext` to handle global state. - Add auto-fetch `organizationProfiles` into `UserContext` every time session refresh and listen to firebase updates. - Directly saved to `Session storage` which will save quotas and ensure speed. --- package-lock.json | 8 ++-- package.json | 2 +- src/App.tsx | 35 +++++++--------- src/components/Home/OrganizationCard.tsx | 6 +-- src/context/SavedContext.tsx | 53 ------------------------ src/context/UserContext.tsx | 43 +++++++++++++++---- src/hooks/index.ts | 2 +- src/hooks/useSaved.ts | 13 ------ src/hooks/useSavedOrgs.ts | 41 ++++++++++++++++++ src/pages/Home.tsx | 21 +++------- src/pages/Saved.tsx | 6 +-- src/utils/firebase/firebaseUtils.ts | 46 +++++++++++--------- src/utils/firebase/index.ts | 2 +- src/utils/firebase/userProfile.ts | 2 +- 14 files changed, 138 insertions(+), 142 deletions(-) delete mode 100644 src/context/SavedContext.tsx delete mode 100644 src/hooks/useSaved.ts create mode 100644 src/hooks/useSavedOrgs.ts diff --git a/package-lock.json b/package-lock.json index 6899f39..9da2e1c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,7 +15,7 @@ "@mui/lab": "^6.0.0-beta.15", "@mui/material": "^6.1.7", "@mui/x-date-pickers": "^7.22.2", - "@zl-asica/react": "^0.3.0", + "@zl-asica/react": "^0.3.4", "date-fns": "^4.1.0", "es-toolkit": "^1.27.0", "firebase": "^11.0.2", @@ -3231,9 +3231,9 @@ } }, "node_modules/@zl-asica/react": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/@zl-asica/react/-/react-0.3.0.tgz", - "integrity": "sha512-gYe/CYo84QKnlWW0IPgtLdZd8shK9cMG7p95NWhIgR0azI90X+v0A61Npe+doNkvGVFGuYRWO1qHzyB2yttWGA==", + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/@zl-asica/react/-/react-0.3.4.tgz", + "integrity": "sha512-FPQfMvh92HHtV7kBXx0yQItQeHaQBS1hSdVtWybV02Y2IRdvJwZVofKnlSC6qIP7f5yo+0WXcx5SgTEPpl8Lew==", "license": "MIT", "engines": { "node": ">=16.0.0" diff --git a/package.json b/package.json index 2bcb583..b8e2788 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,7 @@ "@mui/lab": "^6.0.0-beta.15", "@mui/material": "^6.1.7", "@mui/x-date-pickers": "^7.22.2", - "@zl-asica/react": "^0.3.0", + "@zl-asica/react": "^0.3.4", "date-fns": "^4.1.0", "es-toolkit": "^1.27.0", "firebase": "^11.0.2", diff --git a/src/App.tsx b/src/App.tsx index c20263d..5b427b2 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -4,7 +4,6 @@ import { ThemeProvider } from '@mui/material'; import { BrowserRouter as Router } from 'react-router-dom'; import { UserProvider } from '@/context/UserContext'; -import { SavedProvider } from '@/context/SavedContext'; import { EventsProvider } from '@/context/EventsContext'; import AppRoutes from '@/routes'; @@ -17,25 +16,23 @@ const App = () => { - -
- -
-
- {/* Main content area where pages will render */} - -
+
+ +
+
+ {/* Main content area where pages will render */} + +
- {/* Bottom Navigation with React Router links */} -
- -
- + {/* Bottom Navigation with React Router links */} +
diff --git a/src/components/Home/OrganizationCard.tsx b/src/components/Home/OrganizationCard.tsx index a212508..e2d221c 100644 --- a/src/components/Home/OrganizationCard.tsx +++ b/src/components/Home/OrganizationCard.tsx @@ -16,7 +16,7 @@ import { lighten, useTheme } from '@mui/material/styles'; import { useEffect, useState } from 'react'; import { useToggle } from '@zl-asica/react'; -import { useSaved } from '@/hooks'; +import { useSavedOrgs } from '@/hooks'; import { DonationModal } from '@/components/common'; @@ -25,7 +25,7 @@ const OrganizationCard: React.FC<{ organization: OrganizationProfile }> = ({ }) => { const theme = useTheme(); const [isExpanded, toggleExpand] = useToggle(); - const { savedOrgs, toggleSavedOrg } = useSaved(); + const { savedOrgs, updateSavedOrgs } = useSavedOrgs(); const isSaved = savedOrgs.some((org) => org.uid === organization.uid); const [isModalOpen, toggleModal] = useToggle(); const [checkedItems, setCheckedItems] = useState([]); @@ -65,7 +65,7 @@ const OrganizationCard: React.FC<{ organization: OrganizationProfile }> = ({ action={ diff --git a/src/context/SavedContext.tsx b/src/context/SavedContext.tsx deleted file mode 100644 index 3e582f9..0000000 --- a/src/context/SavedContext.tsx +++ /dev/null @@ -1,53 +0,0 @@ -import { createContext, useState, useContext, useEffect } from 'react'; - -import { UserContext } from '@/context/UserContext'; - -interface SavedContextProps { - savedOrgs: OrganizationProfile[]; - toggleSavedOrg: (org: OrganizationProfile) => void; -} - -const SavedContext = createContext(undefined); - -const SavedProvider = ({ children }: { children: React.ReactNode }) => { - const [savedOrgs, setSavedOrgs] = useState([]); - const { user, updateProfile } = useContext(UserContext); - - useEffect(() => { - if (user?.role === 'donor') { - // Populate savedOrgs from the user's `saved` array - const donorProfile = user as DonorProfile; - setSavedOrgs(donorProfile.saved || []); - } - }, [user]); - - const toggleSavedOrg = async (org: OrganizationProfile): Promise => { - if (!user || user.role !== 'donor') return; - - const donorProfile = user as DonorProfile; - const savedArray = donorProfile.saved || []; - - const updatedSaved = - savedArray.length > 0 - ? savedArray.some((o) => o.uid === org.uid) - ? savedArray.filter((o) => o.uid !== org.uid) - : [...savedArray, org] - : [org]; - - try { - await updateProfile({ saved: updatedSaved }); - setSavedOrgs(updatedSaved); - } catch (error) { - console.error('Error toggling saved organization:', error); - alert('Failed to update saved organizations. Please try again.'); - } - }; - - return ( - - {children} - - ); -}; - -export { SavedContext, SavedProvider }; diff --git a/src/context/UserContext.tsx b/src/context/UserContext.tsx index f62505e..356b702 100644 --- a/src/context/UserContext.tsx +++ b/src/context/UserContext.tsx @@ -1,14 +1,21 @@ import { createContext, useState, useEffect } from 'react'; import { onAuthStateChanged } from 'firebase/auth'; import type { NavigateFunction } from 'react-router-dom'; -import { useLocalStorage } from '@zl-asica/react'; +import { useLocalStorage, useSessionStorage } from '@zl-asica/react'; import LoadingCircle from '@/components/common/LoadingCircle'; -import { loginUser, logoutUser, auth, updateDocument } from '@/utils/firebase'; +import { + loginUser, + logoutUser, + auth, + updateDocument, + getAllOrganizationProfiles, +} from '@/utils/firebase'; interface UserContextType { user: User | undefined; + organizationProfiles: OrganizationProfile[]; loading: boolean; login: (userType: UserType, navigate: NavigateFunction) => Promise; logout: (navigate: NavigateFunction) => Promise; @@ -20,14 +27,21 @@ const UserContext = createContext({} as UserContextType); const UserProvider = ({ children }: { children: React.ReactNode }) => { const { value: user, setValue: setUser } = useLocalStorage( 'user', - // eslint-disable-next-line + // eslint-disable-next-line unicorn/no-useless-undefined undefined ); + const { value: organizationProfiles, setValue: setOrganizationProfiles } = + useSessionStorage('organizationProfiles', []); const [loading, setLoading] = useState(true); // Monitor auth state changes useEffect(() => { - const unsubscribe = onAuthStateChanged(auth, async (firebaseUser) => { + let unsubscribeProfiles: (() => void) | undefined; + + if (organizationProfiles.length === 0) { + unsubscribeProfiles = getAllOrganizationProfiles(setOrganizationProfiles); + } + const unsubscribeAuth = onAuthStateChanged(auth, async (firebaseUser) => { if (firebaseUser) { if (!user) { // if user logged in but not in local storage @@ -40,7 +54,10 @@ const UserProvider = ({ children }: { children: React.ReactNode }) => { setLoading(false); // Stop loading spinner }); - return () => unsubscribe(); + return () => { + if (unsubscribeProfiles) unsubscribeProfiles(); + unsubscribeAuth(); + }; }, []); // Handle login @@ -78,15 +95,16 @@ const UserProvider = ({ children }: { children: React.ReactNode }) => { }; // Handle profile update - const updateProfile = async (updates: Partial): Promise => { + const updateProfile = async ( + updates: Partial + ): Promise => { if (!user) { console.error('No user is currently logged in.'); return; } try { - const collectionName = user.role === 'donor' ? 'users' : 'organizations'; - await updateDocument(collectionName, user.uid, updates); + await updateDocument(user.role, user.uid, updates); setUser((prev) => (prev ? { ...prev, ...updates } : undefined)); // Update local state } catch (error) { console.error('Error updating profile:', error); @@ -96,7 +114,14 @@ const UserProvider = ({ children }: { children: React.ReactNode }) => { return ( {loading ? : children} diff --git a/src/hooks/index.ts b/src/hooks/index.ts index ac0028e..dc315ab 100644 --- a/src/hooks/index.ts +++ b/src/hooks/index.ts @@ -1,3 +1,3 @@ export { default as useUser } from './useUser'; -export { default as useSaved } from './useSaved'; export { default as useEvents } from './useEvents'; +export { default as useSavedOrgs } from './useSavedOrgs'; diff --git a/src/hooks/useSaved.ts b/src/hooks/useSaved.ts deleted file mode 100644 index 44df0cc..0000000 --- a/src/hooks/useSaved.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { useContext } from 'react'; - -import { SavedContext } from '@/context/SavedContext'; - -const useSaved = () => { - const context = useContext(SavedContext); - if (!context) { - throw new Error('useSaved must be used within a SavedProvider'); - } - return context; -}; - -export default useSaved; diff --git a/src/hooks/useSavedOrgs.ts b/src/hooks/useSavedOrgs.ts new file mode 100644 index 0000000..99a47df --- /dev/null +++ b/src/hooks/useSavedOrgs.ts @@ -0,0 +1,41 @@ +import useUser from './useUser'; + +const useSavedOrgs = () => { + const { user, updateProfile } = useUser(); + + if (!user || user.role !== 'donor') { + return { + savedOrgs: [], + updateSavedOrgs: async () => { + console.warn('This user is not a donor.'); + }, + }; + } + + const donorProfile = user as DonorProfile; + const savedOrgs = donorProfile.saved || []; + + const updateSavedOrgs = async (org: OrganizationProfile): Promise => { + const isAlreadySaved = savedOrgs.some( + (organization: OrganizationProfile) => organization.uid === org.uid + ); + + // If exists, remove; else add + const updatedSaved = isAlreadySaved + ? savedOrgs.filter( + (organization: OrganizationProfile) => organization.uid !== org.uid + ) + : [...savedOrgs, org]; + + try { + await updateProfile({ saved: updatedSaved }); + } catch (error) { + console.error('Error toggling saved organization:', error); + alert('Failed to update saved organizations. Please try again.'); + } + }; + + return { savedOrgs, updateSavedOrgs }; +}; + +export default useSavedOrgs; diff --git a/src/pages/Home.tsx b/src/pages/Home.tsx index 3b270cb..26a8175 100644 --- a/src/pages/Home.tsx +++ b/src/pages/Home.tsx @@ -1,27 +1,18 @@ import { Box, Typography } from '@mui/material'; import { filter, lowerCase, some } from 'es-toolkit/compat'; -import { useState, useEffect } from 'react'; +import { useState } from 'react'; + +import { useUser } from '@/hooks'; import { SearchBar } from '@/components/common'; import OrganizationCard from '@/components/Home/OrganizationCard'; -import { getAllOrganizationProfiles } from '@/utils/firebase/firebaseUtils'; - const Home = () => { const [searchQuery, setSearchQuery] = useState(''); // New state for search query - const [organizations, setOrganizations] = useState([]); - - useEffect(() => { - const fetchOrganizations = async () => { - const data = await getAllOrganizationProfiles(); - setOrganizations(data); - }; - - fetchOrganizations(); - }, []); + const { organizationProfiles } = useUser(); // Get organization profiles from context // Filtered organizations based on search query - const filteredOrganizations = filter(organizations, (org) => { + const filteredOrganizations = filter(organizationProfiles, (org) => { const searchTerm = lowerCase(searchQuery); return ( lowerCase(org.name).includes(searchTerm) || @@ -30,7 +21,7 @@ const Home = () => { ); }); - return organizations.length > 0 ? ( + return organizationProfiles.length > 0 ? (
{ - const { savedOrgs, toggleSavedOrg } = useSaved(); + const { savedOrgs, updateSavedOrgs } = useSavedOrgs(); return ( @@ -15,7 +15,7 @@ const Saved = () => { toggleSavedOrg(org)} + onRemove={() => updateSavedOrgs(org)} /> )) ) : ( diff --git a/src/utils/firebase/firebaseUtils.ts b/src/utils/firebase/firebaseUtils.ts index 513b381..f801c46 100644 --- a/src/utils/firebase/firebaseUtils.ts +++ b/src/utils/firebase/firebaseUtils.ts @@ -5,7 +5,7 @@ import { getDoc, getDocs, setDoc, - updateDoc, + onSnapshot, } from 'firebase/firestore'; import { db } from './firebaseConfig'; @@ -29,11 +29,11 @@ const getOrCreateDocument = async >( if (docSnap.exists()) { return docSnap.data() as T; // Return existing document data - } else { - await setDoc(docRef, defaultData); - console.info(`New ${collectionName} profile created.`); - return defaultData; // Return the newly created document data } + + await setDoc(docRef, defaultData); + console.info(`New ${collectionName} profile created.`); + return defaultData; // Return the newly created document data } catch (error) { console.error(`Error in getOrCreateDocument for ${collectionName}:`, error); return undefined; // Return undefined on failure @@ -55,7 +55,7 @@ const updateDocument = async ( ): Promise => { try { const docRef = doc(db, collectionName, uid); - await updateDoc(docRef, updates); + await setDoc(docRef, updates, { merge: true }); // Merge updates with existing data console.info(`Document in ${collectionName} updated successfully.`); } catch (error) { console.error(`Error updating document in ${collectionName}:`, error); @@ -64,28 +64,36 @@ const updateDocument = async ( }; /** - * Get all organization profiles from Firestore. + * Listen to all organization profiles in Firestore. * - * @returns A promise that resolves to an array of OrganizationProfile objects. + * @param callback A function to update the state with the latest organization profiles. + * @returns A function to unsubscribe from the Firestore listener. */ -const getAllOrganizationProfiles = async (): Promise => { +const getAllOrganizationProfiles = ( + callback: (profiles: OrganizationProfile[]) => void +): (() => void) => { try { const organizationsCollection = collection(db, 'organizations'); - const snapshot = await getDocs(organizationsCollection); - if (snapshot.empty) { - console.info('No organization profiles found.'); - return []; - } + // Subscribe to Firestore collection updates + const unsubscribe = onSnapshot(organizationsCollection, (snapshot) => { + if (snapshot.empty) { + console.info('No organization profiles found.'); + callback([]); + return; + } + + const profiles: OrganizationProfile[] = snapshot.docs.map((doc) => { + return { ...doc.data(), uid: doc.id } as OrganizationProfile; + }); - const profiles: OrganizationProfile[] = snapshot.docs.map((doc) => { - return { ...doc.data(), uid: doc.id } as OrganizationProfile; + callback(profiles); }); - return profiles; + return unsubscribe; // cleanup } catch (error) { - console.error('Error fetching organization profiles:', error); - return []; + console.error('Error listening to organization profiles:', error); + throw error; } }; diff --git a/src/utils/firebase/index.ts b/src/utils/firebase/index.ts index 9c37694..190097d 100644 --- a/src/utils/firebase/index.ts +++ b/src/utils/firebase/index.ts @@ -1,3 +1,3 @@ export { loginUser, logoutUser } from './auth'; export { auth } from './firebaseConfig'; -export { updateDocument } from './firebaseUtils'; +export { updateDocument, getAllOrganizationProfiles } from './firebaseUtils'; diff --git a/src/utils/firebase/userProfile.ts b/src/utils/firebase/userProfile.ts index 3345570..297f1b0 100644 --- a/src/utils/firebase/userProfile.ts +++ b/src/utils/firebase/userProfile.ts @@ -52,7 +52,7 @@ const getDonorProfile = async ( saved: [], }; - return getOrCreateDocument('users', uid, defaultProfile); + return getOrCreateDocument('donor', uid, defaultProfile); }; const getOrganizationProfile = async (