Im working on a chat app, using firebase and javascript. I encountered a problem, when I switch receivers multiple times, the message that I sent fetches a few times while the messages is sent only once to the database.
JavaScript
x
14
14
1
var select = document.getElementById("odbiorcy");
2
3
select.addEventListener("change", function handleChange(event) {
4
receiver = select.options[select.selectedIndex].text;
5
console.log("gonna fetch");
6
document.getElementById("messages").innerHTML = "";
7
fetchChat = db.ref("messages/" + username + "/" + receiver + "/");
8
fetchChat.on("child_added", function (snapshot) {
9
const messages = snapshot.val();
10
const msg = "<li>" + messages.usr + " : " + messages.msg + "</li>";
11
document.getElementById("messages").innerHTML += msg;
12
});
13
});
14
Here is how it looks when it fetches, after a switch receivers a few times
As you can see, the first 3 messages that I’ve sent/received where fine, it was only until I switch the receiver that the message I have sent was duplicated on fetch.
Advertisement
Answer
It sounds like you should detach the existing listener when switching receivers in your code.
Something like:
JavaScript
1
20
20
1
var path, listener;
2
select.addEventListener("change", function handleChange(event) {
3
// 👇
4
if (listener) {
5
path.off("child_added", listener)
6
}
7
8
receiver = select.options[select.selectedIndex].text;
9
console.log("gonna fetch");
10
document.getElementById("messages").innerHTML = "";
11
fetchChat = db.ref("messages/" + username + "/" + receiver + "/");
12
// 👇
13
listener = fetchChat.on("child_added", function (snapshot) {
14
const messages = snapshot.val();
15
const msg = "<li>" + messages.usr + " : " + messages.msg + "</li>";
16
document.getElementById("messages").innerHTML += msg;
17
});
18
path = fetchChat; // 👈
19
});
20