简体   繁体   中英

Unable to get doc id in Firebase

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM