Home > Blockchain >  How to remove the item you click on from the Firestore?
How to remove the item you click on from the Firestore?

Time:07-13

I have created banks displayed from the database in the form of cards. How can I take the id of the document I click on and delete this card from the database?

function getBanks() {
  db.collection("banks").onSnapshot((snapshot) => {
    let banks = [];
    snapshot.docChanges().forEach((change) => {
      const bank = change.doc.data();
      if (change.type === "added") {
        banks.push(bank);
        generateBanks([bank]);
      } else if (change.type === "removed") {
        console.log("Removed bank: ", bank );
      }
    });
  });
}

function generateBanks(banks) {
  banks.forEach((bank) => {
    ...
    const bank_delete_el = document.createElement("button");
    bank_delete_el.classList.add("delete");
    bank_delete_el.innerText = "Delete";

    });
  });
}

CodePudding user response:

You can try adding the id of the document as a data-attribute, eg:

function generateBanks(banks) {
  banks.forEach((bank) => {
    ...
    const bank_delete_el = document.createElement("button");
    benk_delete_el.setAttribute("bank-id", bank.id); // add the id as data attribute
    bank_delete_el.classList.add("delete");
    bank_delete_el.innerText = "Delete";

    });
  });
}

This will create the button as

<button  data-bank-id="some-id-123">
  Delete
</button>

Then when you click the delete button you can get the id and delete it from firestore

// on click -> get button element, then
const bankId = myButton.getAttribute("bank-id");

db.collection("banks").doc(bankId).delete().then(() => {
    // ...
});

CodePudding user response:

Here is a simple example using click event listener and firebase delete:

function generateBanks(banks) {
  banks.forEach((bank) => {
    ...
    const bank_delete_el = document.createElement("button");
    bank_delete_el.classList.add("delete");
    bank_delete_el.innerText = "Delete";

    bank_delete_el.addEventListener("click", (_event) => {
      console.log("Deleting bank...", bank);
      db.collection("banks").doc(bank.id).delete()
        .then(() => {
          console.log("Bank successfully deleted!");
        })
        .catch((error) => {
          console.error("Error removing Bank: ", error);
        });
    });
  });
}

Here are the docs for addEventListener and firebase delete documents.

Also it looks like your docChanges body is missing the id field for new banks, whitch is required for deletion.

const bank = change.doc.data();
// Should be 
const bank = {
  id: change.doc.id,
  ...change.doc.data(),
};
  • Related