Retrieving the updated list after a child has been deleted from the Firebase Database

According to the documentation, the DataSnapshot received in the child_removed callback contains the old data for the removed child.

I have a scenario where I am adding data using push and then trying to access the next value after the top child is removed from my database. Here is what I have attempted so far:

var ref = firebase.database().ref("Windsor boyss").limitToFirst(1);
    ref.on("child_removed", function(snapshot) {
        ref.once("value", function(snapshot) {
            snapshot.forEach(function(childSnapshot) {
                console.log("Child is ", childSnapshot.val);
            });
        });
    }); 

For instance, if the username 'javedh' is removed, the EventListener should trigger and print Child is tjaved, which is the new top value in the database after the removal.

https://i.sstatic.net/z7kWA.png

I'm seeking assistance in finding an effective solution to this issue. Thank you!

Answer №1

Doug made a point about how using a nested listener on the same reference is quite uncommon.

The more common approach would be something like this with on("value":

var ref = firebase.database().ref("Windsor boys").limitToFirst(1);
ref.on("value", function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
        console.log("Child is ", childSnapshot.val);
    });
}); 

Update: It seems that the issue might stem from the fact that your ref.once("value" is being retrieved from the local (in memory) cache of the snapshot, which at that moment contains no data.

I managed to find a workaround by creating a new query to listen to within the callback, instead of listening to the same query (which you referred to as ref):

var ref = firebase.database().ref("Windsor boys");
var query = ref.limitToFirst(1);
query.on("child_removed", function(snapshot) {
  console.log("Child "+snapshot.val()+" was removed");
  ref.limitToFirst(1).once("value", function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
      console.log("First child is "+childSnapshot.val());
    });
  });
}); 

To see it in action, check out the complete test bed here: https://jsbin.com/feqojey/edit?js,console

Note that there was a missing pair of () after val() in the loop, although that wasn't the root cause of the problem.

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

The JavaScript code is failing to retrieve any data from the API

import React, { Component } from 'react'; export class FetchData extends Component { static displayName = FetchData.name; constructor(props) { super(props); this.state = { users: [], loading: true }; } componentDidMount() { ...

Executing JavaScript in HttpClient or HtmlUnitHow to trigger javascript in HttpClient or HtmlUnit

Currently, I am using the HttpClient POST method to perform a specific action on a website. This involves using Javascript for an ajax connection which generates a unique requestID in the form of var reqID = Math.floor(Math.random()*1000001);. I need to ac ...

What is the process for adding a Contact Us page to a website?

I recently created a website using html, css and Javascript. I would like to include a 'get in touch' page where visitors can send me messages directly on the site. What steps should I take to make this happen? Is it necessary to set up a databas ...

Different ways to save data fetched from a fetch request

I'm fairly new to React and could use some assistance. I am trying to retrieve data from a movie database based on a search term. I have a method called getMovies where I utilize fetch to grab the data. The information is located in data.Search, but I ...

Performing multiple asynchronous tasks using RxJS by running Array.prototype.map in parallel batches or queues

Imagine having an array of variables, such as: [Sasha, Misha, Caitlyn, ...String] (string[]) with a sizable length of about 10k elements. If you want to run an asynchronous parallel task with these elements, but not all at once like Promise.all, rather in ...

Access array information using AngularJS

Sorry for any language issues. I am trying to figure out how to extract an array data from AngularJS in order to save it using Node.js. This is my AngularJS script: angular.module('myAddList', []) .controller('myAddListController&apos ...

Troubleshooting the issue of AngularJs location.path not successfully transferring parameters

My page has a Login section. Login.html <ion-view view-title="Login" name="login-view"> <ion-content class="padding"> <div class="list list-inset"> <label class="item item-input"> <input type="te ...

Error thrown in JavaScript when calculating the distance

I am currently working on calculating distances between two points, but I keep getting an error that says Uncaught TypeError: a.lat is not a function. function MapLocations() { var i = 0; var infoWindow = new google.map ...

Could this be a problem within my recursive function?

Struggling to iterate through a stack of HTML Elements, I attempted to write a recursive function with no success. In the code snippet below, I'm facing challenges in returning a value from an if statement and ultimately from the function itself. Wh ...

Having trouble with nodeJS when running the command "npm install"?

Can anyone help me understand why I'm encountering issues when running "npm install"? Whenever I run npm install, I am bombarded with numerous errors. npm ERR! Windows_NT 10.0.10586 npm ERR! argv "C:\\Program Files\\nodejs&bsol ...

Managing memory in UIWebView when rendering THREE.js scenes

I am currently working on a game using THREE.js that will be embedded into a UIWebView within an iOS8 app. After analyzing the application in Chrome's developer tools, I have confirmed that there are no memory leaks present. The memory usage reaches ...

Angular directive: inability to pass ng-repeat item through isolate scope

I am currently working on a directive that has an isolate scope. The template of the directive includes an ng-repeat on an element, along with the following code snippet: ng-click="selection(item)" Within the directive's scope definition, I have spe ...

What is the reason behind the ability to access the result of a redux call "immediately" by wrapping it into a promise?

Currently, we are operating in a Redux (with thunk middleware) / React environment. The piece of code below is causing some issues: onMyClick = () => { this.props.mySynchronousActionWhichWillCreateNewReducerState(); this.setState(...my state ch ...

Is there a way to prevent the jsonPayload in stackdriver from automatically converting to a struct format?

When working with a Google Cloud Function, I am logging a simple JSON structure like this: console.info(JSON.stringify({message: 'xxx', data: {status: 200}, status: 200})); However, the log appears in an unreadable format in Stackdriver. How ca ...

flatpickr allows you to synchronize the dates of two date pickers by setting the date of the second one to match the date

Currently utilizing flatpikr from . I'm looking to have the initial date of the return picker set to the same date as the outbound picker upon closing the outbound picker. The code I've written achieves this functionality, but there's an iss ...

Experience the seamless integration of Restful APIs with AngularJS and Querystring parameters

I am currently in the process of developing a web application that includes edit functionality. Currently, I have created a page with a list of records, each containing an ID. When I click on the edit button, it triggers the following: $state.go ...

The Coinbase Pay application fails to compile properly due to a missing Babel loader

Currently, I am working on integrating the coinbase pay sdk into my project. Although I have successfully created a button utilizing their provided examples, I am encountering an issue during the build process which seems to be internal to their SDK. Spec ...

Transform the array into an object containing corresponding key-value pairs

In my dataset, I have an array containing various values: [ { "factor": { "data": "f1", "val": [ "val1" ] } }, { "factor": { "data": "f2", "val": [ "val2" ] ...

Ways to display certain JSON elements

I'm attempting to retrieve a specific part of a JSON file through AJAX and display it in an HTML div. I only want to show a certain object, like the temperature. Here is the AJAX code: $(function () { $.ajax({ 'url': 'http://ap ...

Struggling to capture an error generated by Sequelize within a universal Middleware block

In a test project, I have successfully implemented CLS transaction control in Sequelize using 'cls-hooked'. The transactions work seamlessly both in the command line and with Express. They are injected and managed automatically, rolling back on a ...