Skip to content
Advertisement

Firebase: Javascript fetches messages more than once when switching receivers , while there is only one message in the db

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.

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;
  });
});

Here is how it looks when it fetches, after a switch receivers a few timesmessage fetching multiple 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:

var path, listener;
select.addEventListener("change", function handleChange(event) {
  // 👇
  if (listener) {
    path.off("child_added", listener)
  }

  receiver = select.options[select.selectedIndex].text;
  console.log("gonna fetch");
  document.getElementById("messages").innerHTML = "";
  fetchChat = db.ref("messages/" + username + "/" + receiver + "/");
  // 👇
  listener = fetchChat.on("child_added", function (snapshot) {
       const messages = snapshot.val();
       const msg = "<li>" + messages.usr + " : " + messages.msg + "</li>";
       document.getElementById("messages").innerHTML += msg;
  });
  path = fetchChat; // 👈
});
Advertisement