When changing recipients in Firebase, the Javascript code fetches the same message multiple times even though there is only a single message stored in the database

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.

Answer โ„–1

To ensure smooth switching of receivers in your code, it is recommended to detach the current listener before attaching a new one.

You can achieve this by implementing the following code snippet:

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; // ๐Ÿ‘ˆ
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to update modal content upon clicking a button

I have a scenario where I need to display 2 modals (box1 and box2) in my code with box2 appearing on top of box1. Each modal has its own button, and I want to make sure that box1 appears first. Then, when the user clicks the button in box1, it transitions ...

The script ceased functioning immediately following the inclusion of a case-insensitive search feature and interactive images

In the process of creating my inaugural project featuring a collection of images, I wanted to include a filter/search bar at the top. This bar would dynamically filter the displayed pictures based on user input. For example, typing "Aatrox" into the search ...

Creating a universal representation of the global object in JavaScript that is not tied to any specific implementation

Looking to define the global object in JavaScript with just one line of code: var global = this.global || this; This statement is within the global scope, meaning that in browsers, the this keyword refers to the window object. If this is the first line o ...

Is there a way to dynamically import images in Next JS without having to place them in the public folder?

Currently, I am developing a textbook website in which authors contribute textbook folders containing markdown files and images: textbooks โ”œโ”€โ”€โ”€textbook-1 โ”‚ โ”œโ”€โ”€โ”€images โ”‚ โ””โ”€โ”€โ”€markdown-files โ””โ”€โ”€โ”€textbook-2 โ”œโ”€โ”€ ...

Troubleshooting Ajax contact form's failure to refresh (PHP and Bootstrap 4)

I have successfully implemented this code on one website, but it is not working as expected on another website. It sends the email but refreshes the page and redirects to a contact.php page with a message. Despite double-checking everything, including cha ...

Can you tell me if there is a switch available for hover or mouse enter/mouse leave functions?

I have a series of div elements, each containing several nested div elements. I would like to add hover effects to these div elements. However, I am unsure whether to use the hover or mouseenter function. For instance, when hovering over a div, I want it t ...

"Can you provide instructions on how to set the background to the selected button

How can I change the background color of a selected button in this menu? Here is the code for the menu: <ul id="menu"> <li class="current_page_item"><a class="button" id="showdiv1"><span>Homepage</span></a></ ...

Changing the disabled textfield colour in Material-UI

I am looking to enhance the visibility of disabled text in a textfield by making it darker than the current light color: https://i.sstatic.net/Iw6Dp.png I have attempted to achieve this using the following code snippet: import { withStyles } from ' ...

Utilize JSON data from a service to populate a Bootstrap Modal

I need assistance with populating a Modal using the JSON values I received from a service call. The object structure is simple and understandable, like this: var object = [ {Value1: "Val1", Value2: "Val", Value3: [{a:"a",b:"b"}] }] The ajax call looks ...

Using JavaScript for Array manipulations

Here's a string that I want to convert into an array: "["Arr1","Arr2"]" To achieve the desired format, I need to remove the first and last characters so it looks like this: ["Arr1","Arr2"]. I've attempted using the slice function in this wa ...

Warning: Attention Required for Published NPM Package Fix

After successfully publishing my first package on npm, I encountered a warning when I tried to import it in Codesandbox. There was an error converting '/node_modules/protected-react-routes-generators/src/index.js' from esmodule to commonjs: Canno ...

Unable to utilize ES6 syntax for injecting a service

I am encountering some issues while trying to implement a service into a controller using ES6 syntax. CategoriesService.js export default class CategoriesService { constructor() { this.getCategories = function ($q) { var deferred ...

Validation of user input alongside input masking using jQuery

One issue that I am encountering is that form inputs with assigned masks (as placeholders) are not being validated as empty by jQuery validation. I am using: https://github.com/RobinHerbots/jquery.inputmask https://github.com/1000hz/bootstrap-validator ...

Stop users from inputting dates beyond the current date in Angular 4

Encountering an issue with comparing the date of birth object and today's date object using Moment.js. Even if the entered date is smaller than today's date, it still throws an error. Below is the HTML code: <div class="form-group datepicker ...

Passing Laravel environmental information to a Vue component

I am struggling to retrieve my Stripe keys from my Laravel .env file and pass them into my Vue component. I came across some similar inquiries on Stack Overflow and the Laravel documentation that suggest using the MIX prefix, allowing me to access process. ...

Exploring the Crossroads of JSP and External Javascript Documents

I am new to using external JavaScript files (*.js). I have my JSP file ready, but my manager wants me to incorporate graphics into it. After searching, I found some *.js files. However, I am unsure of how to connect them with my JSP page. I need a way to ...

Loading React router on every route page

<BrowserRouter> <div> <Route path={"/"} component={Home} /> <Route path={"/component"} component={AnotherComp} /> <Route path={"*"} component={NotFound} /> </div> </ ...

Is it possible to utilize a library from one repository and integrate it into a different repository's web application through Webpack?

I have a collection of Vue.js components in a library, and I also have a Vue web application that imports these components. Both are using Webpack and are stored in separate repositories. Prior to utilizing webpack, I was using browserify-hmr and could ea ...

Triggering a re-render in React

There are times when I find myself needing to trigger a re-render while still in the middle of executing a function. As a solution, I've developed a method using the state variable my_force_update. Basically, I change it to a random value when I want ...

What is the best way to delete a jQuery.bind event handler that has been created for an event

I have a div and I need to assign two scroll functions to it, but I also want to remove one of them after a certain condition is met. <div id="div1" class="mydivs"> something </div> <div id="div2">Some crap here</div> <script&g ...