Skip to content

Commit

Permalink
fix: local cache enable, duplicate codes removed. (#12)
Browse files Browse the repository at this point in the history
1. Enable Firebase local cache.
2. Removed duplicate codes in hooks.
3. Improved error handling.
4. Temp comment out fetch course data.
  • Loading branch information
ZL-Asica authored Oct 18, 2024
1 parent e37d73a commit 87b8d32
Show file tree
Hide file tree
Showing 6 changed files with 42 additions and 71 deletions.
6 changes: 4 additions & 2 deletions src/components/Profile/EditProfile.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import React from 'react';

import { useAuthState } from '@auth/useAuthState';
import useCourses from '@data/useCourses';
import useMajors from '@data/useMajors';
import useEditProfileForm from '@hooks/useEditProfileForm';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import {
Expand All @@ -19,12 +21,12 @@ import { useNavigate } from 'react-router-dom';

const EditProfile = () => {
const [user] = useAuthState();
const majorsList = useMajors();
const coursesList = useCourses();
const {
formData,
majorsList,
selectedMajors,
setSelectedMajors,
coursesList,
selectedCourses,
setSelectedCourses,
handleInputChange,
Expand Down
13 changes: 6 additions & 7 deletions src/hooks/data/useUserProfile.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useEffect, useState } from 'react';

import { getMatchedUserUids } from '@firestore/matches';
import { fetchUserProfile, updateUserProfile } from '@firestore/userProfile';
import { fetchUserProfile } from '@firestore/userProfile';

export default function useUserProfile(user) {
const [userProfile, setUserProfile] = useState(null);
Expand All @@ -17,13 +17,12 @@ export default function useUserProfile(user) {
const { profile } = await fetchUserProfile(user.uid);

if (profile) {
if (!profile.locationPreference) {
// Add locationPreference field if it does not exist
profile.locationPreference = { inPerson: true, online: true };
// Update the user profile in Firestore
await updateUserProfile(user.uid, { locationPreference: profile.locationPreference });
}
setUserProfile(profile);

if (profile.major === '' || profile.year === '') {
setLoading(false);
return;
}
setRequestedUsers(new Set(profile.outgoingMatches.map((match) => match.requestedUser)));

const matchedUids = await getMatchedUserUids(user.uid);
Expand Down
21 changes: 4 additions & 17 deletions src/hooks/useEditProfileForm.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
import { useEffect, useState } from 'react';

import { getMajors, getCourses } from '@firestore/general';
import { getUserProfile, updateUserProfile } from '@firestore/userProfile';
import { fetchUserProfile, updateUserProfile } from '@firestore/userProfile';

const useEditProfileForm = (user) => {
const [loading, setLoading] = useState(true);
const [majorsList, setMajorsList] = useState([]);
const [selectedMajors, setSelectedMajors] = useState([]);
const [coursesList, setCoursesList] = useState([]);
const [selectedCourses, setSelectedCourses] = useState([]);

const [formData, setFormData] = useState({
name: '',
email: '',
Expand All @@ -30,14 +26,7 @@ const useEditProfileForm = (user) => {
const fetchProfileMajorsAndCourses = async () => {
if (user && user.uid) {
try {
const [data, majorsFromDb, coursesFromDb] = await Promise.all([
getUserProfile(user.uid),
getMajors(),
getCourses(),
]);
setMajorsList(majorsFromDb);
setCoursesList(coursesFromDb); // Set available courses

const { profile: data } = await fetchUserProfile(user.uid);
if (data) {
setFormData({
name: data.name || '',
Expand All @@ -46,8 +35,8 @@ const useEditProfileForm = (user) => {
major: data.major || '',
year: data.year || '',
description: data.description || '',
inPerson: data.locationPreference.inPerson,
online: data.locationPreference.online,
inPerson: data.locationPreference.inPerson || false,
online: data.locationPreference.online || false,
});
setSelectedMajors(data.major ? data.major.split(',') : []);
setSelectedCourses(data.listOfCourses || []);
Expand Down Expand Up @@ -119,10 +108,8 @@ const useEditProfileForm = (user) => {
return {
formData,
setFormData,
majorsList,
selectedMajors,
setSelectedMajors,
coursesList,
selectedCourses,
setSelectedCourses,
handleInputChange,
Expand Down
15 changes: 10 additions & 5 deletions src/utils/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,16 @@ export const handleSignIn = async () => {
if (user) {
alreadyExist = await checkUserProfile(user);
}
const res = await fetchAndStoreClassData();
if (res) {
console.clear();
console.log('Class data fetched and stored:', res);
}
// ! TEMPORARY REMOVE: Fetch and store class data
// TODO: uncomment this code after the demo

// const res = await fetchAndStoreClassData();
// console.clear();
// if (res) {
// console.warn('Class data fetched and stored:', res);
// } else {
// console.warn('Classes not update:', res);
// }
return alreadyExist;
};

Expand Down
16 changes: 14 additions & 2 deletions src/utils/firebaseConfig.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';
import { getFirestore } from 'firebase/firestore';
import {
CACHE_SIZE_UNLIMITED,
initializeFirestore,
persistentLocalCache,
persistentSingleTabManager,
} from 'firebase/firestore';

const firebaseConfig = {
apiKey: 'AIzaSyAtUHyFNDDtuPVwmH9mNCXa6o2qE_kF6OA',
Expand All @@ -15,5 +20,12 @@ const firebaseConfig = {
// Initialize Firebase
const app = initializeApp(firebaseConfig);

export const db = getFirestore(app);
// Enable IndexedDB persistence with single-tab manager
export const db = initializeFirestore(app, {
localCache: persistentLocalCache({
tabManager: persistentSingleTabManager(),
cacheSizeBytes: CACHE_SIZE_UNLIMITED,
}),
});

export const auth = getAuth(app);
42 changes: 4 additions & 38 deletions src/utils/firestore/classData.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,20 +32,20 @@ const checkAndInsertLatestTerm = async () => {

return LatestTermID;
} catch (error) {
console.error('Error handling latest term:', error);
return null;
throw new Error(`Error handling latest term: ${error}`);
}
};

// Gathering class data from API and storing in Firestore
export const fetchAndStoreClassData = async () => {
try {
const LatestTermID = await checkAndInsertLatestTerm();
if (!LatestTermID) return true;
if (!LatestTermID) return false;

const ClassResponse = await fetch(`https://cdn.dil.sh/paper-data/${LatestTermID}.json`);
if (!ClassResponse.ok)
if (!ClassResponse.ok) {
throw new Error(`Failed to fetch class data: ${ClassResponse.statusText}`);
}

const ClassData = await ClassResponse.json();

Expand Down Expand Up @@ -84,37 +84,3 @@ export const fetchAndStoreClassData = async () => {
return false;
}
};

// Fetch all class data from Firestore (for a specific subject)
export const fetchClassData = async (subject) => {
try {
const classDocRef = doc(collection(db, 'courseData'), subject);
const classSnapshot = await getDoc(classDocRef);

if (!classSnapshot.exists()) {
throw new Error(`No class data found for subject ${subject} in Firestore`);
}

return classSnapshot.data().numbers;
} catch (error) {
console.error('Error fetching class data:', error);
return null;
}
};

// Fetch by Specific subject
export const fetchBySubject = async (subject) => {
try {
const classDocRef = doc(collection(db, 'courseData'), subject);
const classSnapshot = await getDoc(classDocRef);

if (!classSnapshot.exists()) {
throw new Error(`No class data found for subject ${subject} in Firestore`);
}

return classSnapshot.data().numbers;
} catch (error) {
console.error('Error fetching class data:', error);
return null;
}
};

0 comments on commit 87b8d32

Please sign in to comment.