Skip to content

Commit

Permalink
feat: time-preferences backend (#8)
Browse files Browse the repository at this point in the history
- Add a hook to fetch and store user's timePreferences.
- Add [] timePreferences for new registered users.
- Add logic in userProfile.js to communicate with Firebase.

---------

Co-authored-by: ZL Asica <[email protected]>
  • Loading branch information
WelldoneM and ZL-Asica authored Oct 17, 2024
1 parent 99817e8 commit 68ba805
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 7 deletions.
22 changes: 17 additions & 5 deletions src/components/Profile/TimePreferencesPage.jsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,28 @@
import React, { useState } from 'react';
import React from 'react';

import { Box, Typography, Button } from '@mui/material';
import { useTimePreferences } from '@data/useTimePreferences';
import { Box, Typography, Button, CircularProgress } from '@mui/material';

import TimePreferencesGrid from './TimePreferencesGrid';

export default function TimePreferencesPage() {
const [selectedTimes, setSelectedTimes] = useState([]);
const { selectedTimes, setSelectedTimes, loading, savePreferences } = useTimePreferences();

const handleSavePreferences = () => {
console.log('Selected Times:', selectedTimes);
// Function to save preferences and navigate back to profile page
const handleSavePreferences = async () => {
await savePreferences();
};

if (loading) {
return (
<Box
sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}
>
<CircularProgress />
</Box>
);
}

return (
<Box sx={{ maxWidth: 800, margin: 'auto', padding: 3, alignItems: 'center' }}>
<Typography variant="h4" align="center" gutterBottom>
Expand Down
47 changes: 47 additions & 0 deletions src/hooks/data/useTimePreferences.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { useState, useEffect } from 'react';

import { useAuthState } from '@auth/useAuthState';
import { fetchTimePreferences, saveTimePreferences } from '@firestore/userProfile';
import { useNavigate } from 'react-router-dom';

export const useTimePreferences = () => {
const [selectedTimes, setSelectedTimes] = useState([]);
const [loading, setLoading] = useState(true);
const [user] = useAuthState();
const navigate = useNavigate();

const userId = user?.uid;

// Check if user is authenticated, if not, redirect to home
useEffect(() => {
// Fetch saved time preferences when the component loads
const loadPreferences = async () => {
try {
const fetchedTimes = await fetchTimePreferences(userId);
setSelectedTimes(fetchedTimes);
} catch (err) {
console.error('Failed to load time preferences');
} finally {
setLoading(false);
}
};

loadPreferences();
}, [userId, navigate]);

// Function to save the selected time preferences
const savePreferences = async () => {
try {
await saveTimePreferences(userId, selectedTimes);
} catch (err) {
console.error('Failed to save time preferences');
}
};

return {
selectedTimes,
setSelectedTimes,
loading,
savePreferences,
};
};
34 changes: 32 additions & 2 deletions src/utils/firestore/userProfile.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// User profile operations (get, update, check)
import { db } from '@utils/firebaseConfig';
import { doc, setDoc, getDoc, updateDoc } from 'firebase/firestore';

// Unified function to fetch user profile by UID
// (supports both regular and transaction-based fetches)
export const fetchUserProfile = async (uid, transaction) => {
Expand Down Expand Up @@ -41,6 +40,7 @@ export const checkUserProfile = async (user) => {
outgoingMatches: [],
currentMatches: [],
pastMatches: [],
timePreferences: [], //Addingdefault empty array for storing time preferences
};

// Fetch the user profile to check if it exists
Expand Down Expand Up @@ -95,10 +95,40 @@ export const updateUserProfile = async (uid, updates) => {
console.error('Error updating user profile:', error);
}
};

// Example usage:
// await updateUserProfile(user.uid, {
// name: "New Name",
// email: "[email protected]",
// major: "Computer Science"
// });

// Function to save/update time preferences in Firebase
export const saveTimePreferences = async (uid, selectedTimes) => {
try {
const userDocRef = doc(db, 'users', uid);
await updateDoc(userDocRef, {
timePreferences: selectedTimes, // Update timePreferences field
});
console.log('Time preferences updated successfully.');
} catch (error) {
console.error('Error updating time preferences:', error);
}
};

// Function to fetch time preferences from Firestore
export const fetchTimePreferences = async (uid) => {
try {
const userDocRef = doc(db, 'users', uid);
// Getting the user's document from firebase
const userDocSnap = await getDoc(userDocRef);

if (userDocSnap.exists()) {
const data = userDocSnap.data();
// Return saved timePreferences or empty array if none.
return data.timePreferences || [];
}
} catch (error) {
console.error('Error fetching time preferences:', error);
return [];
}
};

0 comments on commit 68ba805

Please sign in to comment.