Skip to content

Commit

Permalink
optimise getFoodList, added fav count sorting
Browse files Browse the repository at this point in the history
  • Loading branch information
TPH777 committed Jul 25, 2024
1 parent 73d35b7 commit df28686
Show file tree
Hide file tree
Showing 8 changed files with 46 additions and 26 deletions.
1 change: 1 addition & 0 deletions src/components/Search.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ export const Search = ({
<option key="name">Name</option>
<option key="date">Date</option>
<option key="price">Price</option>
<option key="favorites">Favorites</option>
<option key="cuisine">Cuisine</option>
</Form.Select>
</Col>
Expand Down
8 changes: 8 additions & 0 deletions src/functions/Alert.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import swal from "sweetalert";

export function consumersOnly() {
swal({
icon: "warning",
title: "Invalid!",
text: `Only consumers account can save favorites`,
});
}

export function deleteWarning(): Promise<boolean> {
return new Promise((resolve) => {
swal({
Expand Down
23 changes: 8 additions & 15 deletions src/functions/GetFood.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,32 +5,25 @@ import { timestampToDate } from "./Date";

export const getFoodList = async () => {
try {
const foodCollectionRef = collection(db, "food");
const querySnapshot = await getDocs(foodCollectionRef);

const batch = writeBatch(db);
const foodCollectionRef = collection(db, "food"); // reference to food db
const querySnapshot = await getDocs(foodCollectionRef); // get all docs in food db
const batch = writeBatch(db); // Collate updates required

querySnapshot.forEach((doc) => {
const foodItem = doc.data() as FoodItem;

// Check if the food item's date is before the current date
if (foodItem.post && timestampToDate(foodItem.date) < new Date()) {
// Update the document to set post to false in the batch
const foodDocRef = doc.ref;
batch.update(foodDocRef, { post: false });
foodItem.post = false;
batch.update(doc.ref, { post: false });
}
});
await batch.commit(); // Commit the batch update

// Commit the batch update
await batch.commit();

// Fetch the updated data after the batch update
const updatedQuerySnapshot = await getDocs(foodCollectionRef);
const updatedFoodList = updatedQuerySnapshot.docs.map((doc) => ({
const updatedFoodList = querySnapshot.docs.map((doc) => ({
...doc.data(),
id: doc.id,
id: doc.id, // Add food item's doc id to the food list
})) as FoodItem[];

return updatedFoodList;
} catch (error) {
throw error; // Rethrow the error to handle it in the calling component
Expand Down
2 changes: 2 additions & 0 deletions src/pages/Dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ export function Dashboard() {
if (sort === "Date") return a.date > b.date ? 1 : -1;
if (sort === "Price") return a.price > b.price ? 1 : -1;
if (sort === "Cuisine") return a.cuisine > b.cuisine ? 1 : -1;
if (sort === "Favorites")
return a.favoriteCount < b.favoriteCount ? 1 : -1;
return a.name.localeCompare(b.name); // Default by name
});
}, [foodList, search, cuisine, sort]); // Depend on foodList, search, cuisine, and sort to re-create memoized value
Expand Down
2 changes: 2 additions & 0 deletions src/pages/Favorites.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ export function FavoritePage() {
if (sort === "Name") return a.name.localeCompare(b.name);
if (sort === "Price") return a.price > b.price ? 1 : -1;
if (sort === "Cuisine") return a.cuisine > b.cuisine ? 1 : -1;
if (sort === "Favorites")
return a.favoriteCount < b.favoriteCount ? 1 : -1;
return a.date > b.date ? 1 : -1; // Default by date
});
}, [foodList, search, cuisine, business, sort]);
Expand Down
6 changes: 6 additions & 0 deletions src/pages/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { useNavigate } from "react-router-dom";
import { doc, increment, updateDoc } from "firebase/firestore";
import { db } from "../config/firebase";
import { ConCards } from "../components/ConCards";
import { consumersOnly } from "../functions/Alert";

export function Home() {
const [foodList, setFoodList] = useState<FoodItem[]>([]); // State for all posted food items
Expand Down Expand Up @@ -61,6 +62,8 @@ export function Home() {
if (sort === "Name") return a.name.localeCompare(b.name);
if (sort === "Price") return a.price > b.price ? 1 : -1;
if (sort === "Cuisine") return a.cuisine > b.cuisine ? 1 : -1;
if (sort === "Favorites")
return a.favoriteCount < b.favoriteCount ? 1 : -1;
return a.date > b.date ? 1 : -1;
});
}, [foodList, search, cuisine, business, sort]);
Expand All @@ -70,6 +73,9 @@ export function Home() {
const toggleFavorite = useCallback(async (foodId: string) => {
if (!user) {
navigate("/login"); // Redirect to login if not logged in
} else if (!isConsumer) {
consumersOnly(); // Alert businesses that they cant save favorites
return;
} else {
setFavList((prev) => {
const add = !prev.includes(foodId);
Expand Down
25 changes: 15 additions & 10 deletions src/pages/Login.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState } from "react";
import { FormEvent, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import ErrorText from "../components/ErrorText";
import { auth, db, googleProvider } from "../config/firebase";
Expand All @@ -14,32 +14,37 @@ export const LoginPage = () => {

let navigate = useNavigate();

const defaultSignIn = async (e: any) => {
const defaultSignIn = async (e: FormEvent) => {
e.preventDefault();
setAuthenticating(true);
if (!email || !password) {
// Empty field
setError("Please fill in all fields."); // Error Management
return;
}
setAuthenticating(true); // To disable button and show spinner
try {
await signInWithEmailAndPassword(auth, email, password);
navigate("/dashboard");
navigate("/dashboard"); // successful sign in
} catch (error) {
setAuthenticating(false);
setError(getErrorMessage(error));
setError(getErrorMessage(error)); // Error Management
}
};

const googleSignIn = async () => {
setAuthenticating(true);
await signInWithPopup(auth, googleProvider)
setAuthenticating(true); // To disable button and show spinner
await signInWithPopup(auth, googleProvider) // Call firebase authenticator
.then(async (userCredential) => {
const user = userCredential.user;
if (!doc(db, "consumer", user.uid)) {
// Document don't exist (New user)
// Document don't exist (New user - register)
await setDoc(doc(db, "consumer", user.uid), {});
}
navigate("/");
navigate("/"); // successful sign in
})
.catch((error) => {
setAuthenticating(false);
setError(error.message);
setError(error.message); // Error Management
});
};

Expand Down
5 changes: 4 additions & 1 deletion src/pages/Register.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,14 @@ export const RegisterPage = () => {
const navigate = useNavigate();

const signUpWithEmailAndPassword = () => {
if (!name || !email || !password || !confirm) {
if ((!isConsumer && !name) || !email || !password || !confirm) {
// Empty field
setError("Please fill in all fields.");
return;
}

if (password !== confirm) {
// Different password
setError("Passwords do not match.");
return;
}
Expand All @@ -50,6 +52,7 @@ export const RegisterPage = () => {
navigate("/dashboard");
})
.catch((error) => {
// Error management
if (error.code === "auth/weak-password") {
setError("Please enter a stronger password.");
} else if (error.code === "auth/email-already-in-use") {
Expand Down

0 comments on commit df28686

Please sign in to comment.