I have been using ForEach to populate my HTML table.
So far so good but the table is not realtime. I have to reload the function for it to fetch the results again. If I add or delete an entry nothing happens VISUALLY until I reload.
Is there a way to make this realtime?
Code from Firebase Docs:
var query = firebase.database().ref("users").orderByKey();
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
// key will be "ada" the first time and "alan" the second time
var key = childSnapshot.key;
// childData will be the actual contents of the child
var childData = childSnapshot.val();
});
});
Please excuse my poor knowledge on JS, I am working on it.
By using once() you're telling that database that you only want to get the current value and don't care about updates.
The solution to get realtime updates, is to use on(). Since a promise can only resolve once while an on() handler is called for every update, you should use a callback with on():
var query = firebase.database().ref("users").orderByKey();
query.on("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
// key will be "ada" the first time and "alan" the second time
var key = childSnapshot.key;
// childData will be the actual contents of the child
var childData = childSnapshot.val();
});
}, function(error) {
console.error(error);
});
If you care about updating a UI in response to such updates, you'll probably want to use child_ handlers. These get called one level lower in your JSON tree, so in your case for each user that is added/changed/deleted. This allows you to update the UI more directly. For example, the child_added event for the above could be:
var query = firebase.database().ref("users").orderByKey();
query.on("child_added", function(snapshot) {
var key = snapshot.key;
var data = snapshot.val();
// TODO: add an element to the UI with the value and id=key
});
}, function(error) {
console.error(error);
});
Now you can handle the other events with:
query.on("child_changed", function(snapshot) {
// TODO: update the element with id=key in the update to match snapshot.val();
})
query.on("child_removed", function(snapshot) {
// TODO: remove the element with id=key from the UI
})
This and much more is covered pretty extensively in our guide for web developers and in the reference documentation.
Related
I am faced with the problem of retrieving two data values of a single node from my firebase database and reference it in my javascript file but don't know how to go about it. I have been able to retrieve just one data value from a node (in this case "message") but I would like to add "from" as well. Most tutorials just reference one so I am really confused. So how do I get multiple data values?
This is my code...
JS file
exports.sendNotification7 = functions.database.ref('/GroupChat/{Modules}/SDevtChat/{SDevtChatId}/message')
.onWrite(( change,context) =>{
// Grab the current value of what was written to the Realtime Database.
var eventSnapshot = change.after.val();
var str = "New message from System Development Group Chat: " + eventSnapshot;
console.log(eventSnapshot);
var topic = "Management.Information.System";
var payload = {
data: {
name: str,
click_action: "Student_SystemsDevt"
}
};
// Send a message to devices subscribed to the provided topic.
return admin.messaging().sendToTopic(topic, payload)
.then(function (response) {
// See the MessagingTopicResponse reference documentation for the
// contents of response.
console.log("Successfully sent message:", response);
return;
})
.catch(function (error) {
console.log("Error sending message:", error);
});
});
You can read from however many nodes you want in a Cloud Function. However, only one can trigger the function to run.
To read from your database use the following code:
admin.database().ref('/your/path/here').once('value').then(function(snapshot) {
var value = snapshot.val();
});
You will probably want to read from the same place that the Cloud Function was triggered. Use context.params.PARAMETER to get this information. For the example you posted your code would turn out looking something like this:
admin.database().ref('/GroupChat/'+context.params.Modules+'/SDevtChat/'+context.params.SDevtChatId+'/from').once('value').then(function(snapshot) {
var value = snapshot.val();
});
Just trigger your function one level higher in the JSON:
exports.sendNotification7 =
functions.database.ref('/GroupChat/{Modules}/SDevtChat/{SDevtChatId}')
.onWrite(( change,context) =>{
// Grab the current value of what was written to the Realtime Database.
var eventSnapshot = change.after.val();
console.log(eventSnapshot);
var str = "New message from System Development Group Chat: " + eventSnapshot.message;
var from = eventSnapshot.from;
...
I'm trying to access "id" and store it in a variable. So far the code I have is:
var ref = firebase.database().ref("users");
ref.on("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
console.log(childData);
});
});
What I get from above is:
With that I have access to the object itself, but how can I access the property "id"? I'm reading the official documentation but I can't figure it out.
Do this:
var ref = firebase.database().ref("users");
ref.on("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
var id=childData.id;
console.log(childData);
});
});
In the above the location is at users then you use on() method to read data, and using the forEach loop, you iterate inside the pushid and get the values.
To access each one alone you do this var ids=childData.id; or/and var names=childData.name;
Also it is better to use once() as it only reads data once.
You need to get key of parent-node(L2L6vBsd45DFGfh) to access id child
When you use push() method in firebase it will automatic generate unique key for your record.
use set() or update() method to create your own custom keys.
var ref = firebase.database().ref("users");
ref.on("value", function(snapshot) {
var childData = snapshot.val();
var key = Object.keys(childData)[0]; //this will return 1st key.
console.log(childData[key].id);
});
You will use for-loop or forEach to get all keys.
It's been a few months I started learning JavaScript, since I am an IOS developer, I prefer Firebase as my backend for my websites too.
So on today's practice, I used to read Firebase data and alert it to myself, I used this code,
Notice: those code's are only examples and used during my work, and it officially comes from Firebase's documentation.
var query = firebase.database().ref("users").orderByKey();
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
// key will be "ada" the first time and "alan" the second time
var key = childSnapshot.key;
// childData will be the actual contents of the child
var childData = childSnapshot.val();
alert(key); // also tried the (key.value); as well
});
and here is my Firebase structure:
and the output:
It's funny but firebase doesn't update their docs as often as their API changes, even worse if you're using Angular 4+. Try rewriting your code like this below. you need to return a boolean value after iterating a snapshot with forEach:
var query = firebase.database().ref("users").orderByKey();
query.once("value", (function(snapshot) {
snapshot.forEach(function(childSnapshot) {
// key will be "ada" the first time and "alan" the second time
var key = childSnapshot.key;
// childData will be the actual contents of the child
var childData = childSnapshot.val();
alert(key); // also tried the (key.value); as well
return true;
})
)
I'm trying to update a property in a record in Firebase Database, with AngularJS. I can set up a query to find my record:
firebase.database().ref('en/').orderByChild('word').equalTo('the').once('value')
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
console.log(childSnapshot.val())
});
})
I can update my property, if I hardcode in the record's key:
firebase.database().ref('en/-KloeQHDC-mugPjJMAG4').update({ wordFrequency: 111 })
But if I set up a query to find the record and then update it, I get an error message update is not a function:
firebase.database().ref('en/').orderByChild('word').equalTo('the').update({ wordFrequency: 9001 })
Another answer suggests calling update() from inside a forEach loop:
firebase.database().ref('en/').orderByChild('word').equalTo('the').once('value')
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
console.log(childSnapshot.val()); // this works
childSnapshot.ref().update({ wordFrequency: 9001 });
});
});
That returns an error message TypeError: childSnapshot.ref is not a function. I don't see how childSnapshot is a Firebase ref.
Another answer says
When you call update() on a location, Firebase loops over the data
that you pass in (in your case asJson) and for each key performs a
ref.child(key).set(value).
If update() loops over the data, why should I call update() from inside a forEach loop? The documentation doesn't show calling update() from inside a forEach loop.
The Firebase Database SDK provides a Reference.update() method to update data in a single location in a database. Key here is that a Reference is a single location in the database, so it is clear what to update.
My pseudo-code explanation about how multi-path updates work applies to how the database server implements it: given a single location/DatabaseReference it updates each path in the update() call based on that.
A Query can match multiple locations in the database, so it doesn't have an update() method (or set() or remove() for that matter).
To update each location matched by a query, you execute the query and then call update() on each result - either by a child_added listener, or with a value listener and a loop like in your last snippet.
After I posted this question I walked the dog, ate dinner, and then the solution came to me. My new rule is, "The key to Firebase queries is to keep track of the key."
This template is for users to update records in the database. They enter a search term in a form field and click the "Search" button. The $scope.search handler queries the Firebase database and then populates the form fields with the record's properties:
$scope.search = function() {
myFirebase_ref.orderByChild('word').equalTo($scope.word).once('value')
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
$scope.wordKey = childSnapshot.key;
$scope.audioArray = childSnapshot.val().audio;
$scope.ipaArray = childSnapshot.val().ipa;
$scope.language = childSnapshot.val().language;
$scope.longLanguage = childSnapshot.val().longLanguage;
$scope.phonemeArray = childSnapshot.val().phonemes;
$scope.translationArray = childSnapshot.val().translations;
$scope.word = childSnapshot.val().word;
$scope.wordFrequency = childSnapshot.val().wordFrequency;
$scope.$apply();
});
})
.catch(function(error) {
console.error("Authentication failed:", error.message);
});
};
Note at the top of the property assignments I have $scope.wordKey = childSnapshot.key;. I'm keeping track of the record's key.
The user then updates a field. Each field has a button next to it for "Update". Each button goes to a handler. For example, to update the wordFrequency field I have this handler:
$scope.updateFrequencyRank = function() {
firebase.database().ref('en/' + $scope.wordKey).update({ wordFrequency: $scope.wordFrequency })
};
One line of code and it works! Even better, I made an onComplete function to tell me if the update succeeded:
$scope.updateFrequencyRank = function() {
var onComplete = function(error) {
if (error) {
console.log('Update failed');
} else {
console.log('Update succeeded');
}
};
firebase.database().ref('en/' + $scope.wordKey).update({ wordFrequency: $scope.wordFrequency }, onComplete);
};
On Firebase3 I am looking for a way to get to old value from an item in a firebasearray. Is there any way to do it or can we override the child_changed event? The solution should be for firebase 3 javascript SDK.
var commentsRef = firebase.database().ref('post-comments/' + postId);
commentsRef.on('child_changed', function(data) {
// data variable holds new data. I want the old one before the update happened!
});
There is no way to get the old value with an event. If you need that, you'll have to track it yourself.
var commentsRef = firebase.database().ref('post-comments/' + postId);
var oldValue;
commentsRef.on('child_changed', function(snapshot) {
// TODO: compare data.val() with oldValue
...
oldValue = snapshot.val();
});