I am trying to get the doc id of each data entry upon click to delete that specific record, but upon checking it is only showing id of the first entry made in the Firebase.
const deleteRecord = () => {
db.collection("records").onSnapshot((querySnapshot) => {
querySnapshot.forEach((doc) => {
// console.log(doc.id)
let recToDel = document.querySelectorAll(".records")
for (let toDelRecord of recToDel) {
toDelRecord.onclick = () => {
console.log(doc.id)
}
}
})
})
}
The loops are nested, so the last iteration of the querySnapshot.forEach loop is the one that sets the same doc.id for every recToDel dom element.
Fix by looping just one collection and indexing into the other...
let recToDel = Array.from(document.querySelectorAll(".records"));
querySnapshot.docs.forEach((doc, index) => {
if (index < recToDel.length) {
let toDelRecord = recToDel[index];
toDelRecord.onclick = () => {
console.log(doc.id)
}
}
});
If there are fewer .records elements than there are docs, some won't be assigned.
Doing this onSnapshot will cause these assignments to be made every time the collection changes, including on deletes. If that's not your intention, fix by changing to get().