In the process of developing a chat application using Firebase and JavaScript, I have come across an issue. Whenever I switch receivers multiple times, the message I send is fetched multiple times even though it is only sent once to the database.
var select = document.getElementById("odbiorcy");
select.addEventListener("change", function handleChange(event) {
receiver = select.options[select.selectedIndex].text;
console.log("gonna fetch");
document.getElementById("messages").innerHTML = "";
fetchChat = db.ref("messages/" + username + "/" + receiver + "/");
fetchChat.on("child_added", function (snapshot) {
const messages = snapshot.val();
const msg = "<li>" + messages.usr + " : " + messages.msg + "</li>";
document.getElementById("messages").innerHTML += msg;
});
});
After switching receivers multiple times, the appearance of the fetched messages can be seen https://i.sstatic.net/JcYr6.png
Upon closer inspection, the first 3 messages sent and received appeared correctly. However, the issue of message duplication during fetch only emerged after changing the receiver multiple times.