I am new to firebase and quite new to react, I'm developing a shopping list app. I add documents to my db using setDoc()
like that:
const addToFirestore = async () => {
if (tilesToDB.indexOf(tile) === -1) {
setTilesToDB((prev) => [...prev, tile]);
await setDoc(doc(db, 'list', tile.contents), tile);
}
}
The item is added either by clicking on the add button or by clicking outside input field after typing item's name. When i try to delete document in similar fashion, by deleteDoc():
const removeFromFirestore = async (id) => {
const docRef = (db, 'list', id);
await deleteDoc(docRef).then(() => {
console.log("Entire Document has been deleted successfully.")
})
.catch(error => {
console.log(error);
});
}
and then calling the above function by clicking remove button:
onClick={(e) => {
e.preventDefault();
console.log(tile.id, 'tile to remove');
setItems(items.filter((el, i) => i !== items.indexOf(tile)));
removeFromFirestore(tile.contents);
console.log('test', items);
}
i get Uncaught (in promise) TypeError: Cannot use 'in' operator to search for '_delegate' in undefined
The rest of the code works fine, including the setItems()
call in above function, which deletes item in the browser, but it's not subsequently deleted from db. the console.log
call shows that the right document id is being passed to deleteDoc()
. I also made sure to have all the relevant imports.
CodePudding user response:
You are mixing async/await
and .then()/.catch()
. You do NOT want to do this. You will not be happy with the results.
Simply change your code to:
const removeFromFirestore = async (id) => {
const docRef = (db, 'list', id);
try {
await deleteDoc(docRef)
console.log("Entire Document has been deleted successfully.");
} catch(ex) {
console.log(ex);
}
}
Later in your code you call: removeFromFirestore(tile.contents);
Is tile.contents
a valid id
value, which is what removeFromFirestore()
is expecting?
You might consider doing a console.log('docRef path is', docRef.path)
inside removeFromFirestore()
right after giving docRef a value, just to be sure that it is the path you expect it to be.