The Firebase child_changed event may occasionally be missed at random intervals when the browser tab is inactive

I am currently developing a real-time application where one user can enter the app, and all other users connected to that session will receive notifications or payloads of what that user is entering.

Below is the Firebase child_changed listener that every device in the session is listening to:

firebase.database().ref().child('collection')
    .orderByChild('sessionId')
    .equalTo('123') //unique id
    .on('child_changed', function (snapshot) {
    //performing some processing                 
});

Whenever a user enters the app, I update the Firebase document/collection as follows:

var newObject = {},
        fbId = 'Kh8nyd9C1FGeBx229ogyr';// unique id of document to be updated

newObject[fbId] = {
    'sessionId': '123',
    'payLoad': JSON.stringify(payLoad), //different payload for each device listening to the collection within this session
    'lastUpdated': new Date().getTime() //adding a unique timestamp to trigger the child_changed event
};

firebase.database().ref().child('collection').update(newObject);

//rules

"rules": {
    "$uid": {
        "collection": {
            ".read": "auth.uid == $uid",
                ".write": "auth.uid == $uid",
                    ".indexOn": ["sessionlId"]
        }  
    }
}

//data

{
  "Azublidegytttsbmnmnmnm": { //uid
    "collection": {
      "Kh8nyd9C1FGeBx229ogyr": {
        "sessionId": 123,
        "payLoad": {Id: '11', Name: 'John Doe'},
        "lastUpdated": 1543875382963 
      }
    }  
  }
}

The above code works most of the time but misses events if a browser tab remains idle for an extended period. In such cases, it fails to receive events or trigger the child_changed event when a new user enters while another connected user's tab is inactive. Refreshing the browser helps reset the Firebase connection code and restores proper functionality.

Any assistance on ensuring that the child_changed event fires consistently would be greatly appreciated. Alternatively, feel free to suggest any other approaches to address this issue.

I am using version 3.5.3 of the Firebase library.

Thank you!

Answer №1

Recently, I updated my firebase version from 3.5.3 to the latest one. One major change I made was binding the event directly at the specific node instead of listening to the entire JSON collection (previously listened at root level).

OLD CODE:

firebase.database().ref().child('collection')
    .orderByChild('sessionId')
    .equalTo('123') //unique id
    .on('child_changed', function (snapshot) {
    //some processing                 
});

NEW CODE:

firebase.database().ref().child('collection/Kh8nyd9C1FGeBx229ogyr') //Kh8nyd9C1FGeBx229ogyr here is firebase generated node and its unique id
    .on('child_changed', function (snapshot) {
    //some processing                 
});

P.S Make sure to listen at the lowest level for the child_changed event according to Firebase support advice.

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

Deducting time from the present moment

I am facing a scenario where I have 2 strings representing the minute and hour for a specific function to execute at. I aim to validate if the specified minute and hour, present in string format and retrieved from my database, are within a 5-minute window ...

Regular expressions for identifying operands and operators in a calculator application implemented with JavaScript

I am currently working on a JavaScript project to create a basic calculator. I am in need of a way to validate each item in an array of operands (sequences of digits) and operators (+, -, *, /, ** for power). I have managed to create regex patterns for di ...

JavaScript and jQuery - Struggling to retrieve checkbox values

In my dynamically generated (ASP) photo gallery, I have multiple checkboxes. Each checkbox is labeled as 'photos' and contains a unique photo ID in its value attribute. Here's an example of how the checkboxes are structured: <form name=" ...

Before I press enter, what kind of function is evaluated by the Node.JS REPL?

It's interesting how in the Node.JS REPL, the result of the current expression sometimes gets evaluated before hitting enter, which raises questions. I find it puzzling: How does Node.JS determine if I intended to evaluate it or not? Simple calculati ...

Should code in Vuejs be spread out among multiple components or consolidated into a single component?

After spending a significant amount of time working with Vue, I find myself facing a dilemma now that my app has grown in size. Organizing it efficiently has become a challenge. I grasp the concept of components and their usefulness in scenarios where the ...

Create a shape using a series of points without allowing any overlap between the lines

JS fiddle There is an array of coordinates that gets populated by mouse clicks on a canvas. var pointsArray = []; Each mouse click pushes x and y values into this array using a click event. pointsArray.push({x: xVal, y: yVal}); The script iterates thr ...

What is the best way to focus on a specific section of a CSS class name?

Successfully Working Example: HTML: <div class="items"> <div class="item">item 1</div> <div class="prefix-item-suffix">item 2</div> <div class="item">item 3</div> < ...

Updating the content of a list item on the fly using React

After spending all day on this, I am feeling a bit frazzled. Trying to achieve what would take 20 seconds in JQuery has proven to be quite the challenge in React ¯\_(ツ)_/¯ In my application, tags are ranked by importance from 1 to 9. Simple enoug ...

What makes 'Parsing JSON with jQuery' unnecessary?

Just performed an ajax request with a query and noticed that my response is already in the form of a JavaScript object. When I try to parse the JSON using: var obj = jQuery.parseJSON(response); 'obj' turns out to be null, yet I can directly ac ...

Hidden input fields do not get populated by Angular submit prior to submission

I am in the process of implementing a login feature in Angular that supports multiple providers. However, I have encountered an issue with submitting the form as the loginProvider value is not being sent to the server. Below is the structure of my form: &l ...

Modify the position of the CSS background for the Y-axis using jQuery

Let's consider a scenario with the following table: <table> <tr> <td class="t"></td> <td class="e"></td> <td class="s"></td> <td class="t"></td> </ ...

displaying error message after calling API on Node.js express server

I'm currently working on error handling on the front end, using responses from my Express server. The process involves sending data from the front end to the Express server via a POST request. The endpoint (referenced as /endpoint below) then communic ...

Corporate firewall causing issues with AJAX call execution

Currently, I am utilizing jQuery's $.ajax() method to retrieve approximately 26KB of JSONP data. All major browsers including FF, Chrome, IE, and Safari are successfully returning the data from various locations such as work, home, and mobile phone w ...

Can an in-progress NPM package be tested using NPX?

I am currently developing an NPM package that is designed to be used exclusively through npx *, similar to packages like create-nuxt-app. Is there a method to test my package using npx *? Essentially, I want to run my bin script without actually installin ...

"Exploring the power of AngularJS in enhancing Google SEO through strategic page

I'm encountering a problem with displaying page titles in my angular application through Google Webmaster Tools. Despite setting up the title binding using ui-router, the titles are not showing up as expected. <title ng-bind="'Page title | &a ...

Display an array containing date objects in a dropdown menu for users to select from

I am working with an API call that returns an array of objects. Each object in the array contains a date or timestamp in ISO format. Right after my render() method, I have the following code snippet: const pickerItems = this.props.currentData.trips.map(t ...

Issues with EventListeners in Internet Explorer

Similar Inquiry: Issue with MSIE and addEventListener in JavaScript? I am currently attempting to detect a close event on a popup window created by the parent page. The objective is for users to fill out a form and then, via a popup window, grant perm ...

Tips on using MUI Texfield and Redux to update state

I am facing an issue with my input field as I attempt to pass some information before navigating to a different page. The problem lies in the fact that my Redux state is not updating, although the console confirms that the value is being passed correctly. ...

Connect a designated button to a designated modal for a seamless user experience

I am struggling to dynamically change the content of a modal based on different buttons being clicked. The issue lies in trying to reference the div element within JavaScript since I can't have multiple elements with the same ID. As a newcomer to JS, ...

Exploring the functionality of the load event in JQuery for images

I am encountering an issue with the code provided below: <!DOCTYPE html> <html> <head> <style> </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> </hea ...