Skip to content

Commit

Permalink
Removes deleted food's id from consumer fav
Browse files Browse the repository at this point in the history
  • Loading branch information
TPH777 committed Jul 26, 2024
1 parent 0eef88c commit bca7952
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/functions/DeleteFav.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import {
collection,
getDocs,
writeBatch,
query,
where,
} from "firebase/firestore";
import { db } from "../config/firebase";

interface FavList {
favorites: string[];
}

export const deleteFav = async (foodId: string) => {
try {
const favCollectionRef = collection(db, "consumer");
const q = query(
favCollectionRef,
where("favorites", "array-contains", foodId)
);
const querySnapshot = await getDocs(q);
const batch = writeBatch(db);

querySnapshot.forEach((doc) => {
const consumerDoc = doc.data() as FavList;
const updatedFavList = consumerDoc.favorites.filter(
(id) => id !== foodId
);
batch.update(doc.ref, { favorites: updatedFavList });
});

await batch.commit();
} catch (error: any) {
throw error;
}
};
6 changes: 6 additions & 0 deletions src/pages/Dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { getFoodList } from "../functions/GetFood";
import { Spinner } from "react-bootstrap";
import { useAuth } from "../context/Auth";
import { useNavigate } from "react-router-dom";
import { deleteFav } from "../functions/DeleteFav";

export function Dashboard() {
const { user, isConsumer } = useAuth();
Expand Down Expand Up @@ -68,6 +69,11 @@ export function Dashboard() {
await deleteObject(ref(getStorage(), data.imagePath));
await deleteDoc(foodDoc);
setFoodList((prevList) => prevList.filter((food) => food.id !== id));
try {
deleteFav(id); // Delete food item for all conumers that saved it as favorites
} catch (error) {
throw error;
}
deleteSuccess(data.name);
}
} catch (error) {
Expand Down

0 comments on commit bca7952

Please sign in to comment.