diff --git a/src/functions/DeleteFav.tsx b/src/functions/DeleteFav.tsx new file mode 100644 index 0000000..4c6309f --- /dev/null +++ b/src/functions/DeleteFav.tsx @@ -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; + } +}; diff --git a/src/pages/Dashboard.tsx b/src/pages/Dashboard.tsx index dcda884..26b7e0a 100644 --- a/src/pages/Dashboard.tsx +++ b/src/pages/Dashboard.tsx @@ -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(); @@ -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) {