Skip to content

Commit

Permalink
Merge pull request #36 from the-collab-lab/ma-rc-feat/delete-item
Browse files Browse the repository at this point in the history
Issue # 12: Deleting a shopping list item
  • Loading branch information
eternalmaha authored Sep 22, 2024
2 parents 855a7c2 + 439f163 commit a2bcb7f
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 7 deletions.
27 changes: 21 additions & 6 deletions src/api/firebase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
getDoc,
setDoc,
addDoc,
deleteDoc,
collection,
doc,
onSnapshot,
Expand Down Expand Up @@ -294,10 +295,24 @@ export async function updateItem(listPath: string, item: ListItem) {
}
}

export async function deleteItem() {
/**
* TODO: Fill this out so that it uses the correct Firestore function
* to delete an existing item. You'll need to figure out what arguments
* this function must accept!
*/
//delete an item from the list
export async function deleteItem(listPath: string, item: ListItem) {
//reference the item document
const itemDocRef = doc(db, listPath, "items", item.id);
//get the document from firebase
const docSnap = await getDoc(itemDocRef);

// Delete the item from the list in Firestore.
// Should be a simple try-catch block. Try === deletes the item. Catch === logs the error.
// Let's try the deleteDoc from Firestore.
if (docSnap.exists()) {
try {
await deleteDoc(itemDocRef);
alert(`${item.name} has been successfully deleted!`);
} catch (error) {
// If there's an error, log it to the console and throw it.
console.error("Oops! Error deleting Item!", error);
throw error;
}
}
}
20 changes: 19 additions & 1 deletion src/components/ListItem.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import "./ListItem.css";
import { updateItem, ListItem } from "../api";
import { updateItem, deleteItem, ListItem } from "../api";
import { useState } from "react";
import toast from "react-hot-toast";
import { moreThan24HoursPassed } from "../utils";
Expand Down Expand Up @@ -52,6 +52,23 @@ export function ListItemCheckBox({ item, listPath }: Props) {
}
};

const deleteItemHandler = () => {
const isConfirmed = window.confirm("Do you want to delete this item?");

if (isConfirmed) {
try {
deleteItem(listPath as string, item);
} catch (error) {
console.error(`Error deleting ${item.name}`, error);
alert("Error deleting item!");
}
}

if (!isConfirmed) {
return;
}
};

return (
<div className="ListItem">
<label htmlFor={`checkbox-${item.id}`}>
Expand All @@ -67,6 +84,7 @@ export function ListItemCheckBox({ item, listPath }: Props) {
/>
{item.name}
</label>
<button onClick={() => deleteItemHandler()}>Delete Item</button>
</div>
);
}

0 comments on commit a2bcb7f

Please sign in to comment.