I need it to be displayed on the screen after adding a bank to the database. Now the problem is that after adding a bank to the database, all banks from the database are displayed, and even those that have already been added - they are drawn again. How can I draw on the screen one bank that I have added?
// add bank
function sendBankData() {
db.collection("banks").add({
bankName: bankName.value,
interestRate: interestRate.value,
maximumLoan: maximumLoan.value,
minimumDownPayment: minimumDownPayment.value,
loanTerm: loanTerm.value,
});
successfulPopUp();
}
// get bank
function getBanks() {
db.collection("banks").onSnapshot((snapshot) => {
let banks = [];
snapshot.docs.forEach((doc) => {
banks.push({
id: doc.id,
...doc.data(),
});
});
generateBanks(banks);
});
}
function generateBanks(banks) {
banks.forEach((bank) => {
bankItems.innerHTML =
`<div >
<img src="./img/edit-icon1.png" alt="">
<div >
Bank name: <span >`
bank.bankName
`</span>
</div>
<div >
Interest rate: <span >`
bank.interestRate
`</span>
</div>
<div >
Maximum loan: <span >`
bank.loanTerm
`</span>
</div>
<div >
Minimum down payment: <span >`
bank.maximumLoan
`</span>
</div>
<div >
Loan term: <span >`
bank.minimumDownPayment
`</span>
</div>
</div>
`;
});
}
CodePudding user response:
You can listen on document changes and then rerender your banks:
function getBanks() {
db.collection("banks").onSnapshot((snapshot) => {
const banks = [];
if (banks.length === 0) {
// Your first loop for existing banks
snapshot.docs.forEach((doc) => {
banks.push({
id: doc.id,
...doc.data(),
});
});
generateBanks(banks);
}
// Now you can listen for changes
snapshot.docChanges().forEach((change) => {
const bank = {
id: change.doc.id,
...change.doc.data(),
};
// Here you can add your new bank and rerender
if (change.type === "added") {
console.log("Added bank: ", bank);
banks.push(bank );
generateBanks([bank ]);
}
// You can also react on modified and removed objects
if (change.type === "modified") {
console.log("Modified bank: ", bank );
}
if (change.type === "removed") {
console.log("Removed bank: ", bank );
}
});
});
}
For further reading check the docs.