Hello I would like to automatically generate an alert in realtime as soon as a value in my Firebase database has changed. My code looks like this:
try {
var ref = firebase.database().ref("URL").child("1");
ref.on("child_changed", function(snapshot) {
var changedPost = snapshot.val();
alert(changedPost);
});
}
catch(err) {
alert("Error");
}
As you can see the structure of my database is:
Could someone tell me what is wrong with this code and why I don't get an alert when something changes in my database?
I would appreciate an answer.
You're listening for child_changed events, which fires when a property under /URL/1 changes. To instead get called when the value in /URL/1 changes, listen for a value event:
ref.on("value", function(snapshot) {
var changedPost = snapshot.val();
alert(changedPost);
});
Related
I want to do a user search vie search bar.when I enter the last name I should receive data about users if there are matches but i don't know how.
here is my try
searchBar(){
let a=app.database().ref('users/'+app.auth().currentUser.uid).orderByChild('/surname').equalTo('Крюкин');
console.log(a);
}
here is structure of data
Try the following:
searchBar(){
let a=app.database().ref('users');
a.orderByChild('surname').equalTo('Крюкин').on('value',((snapshot) => {
snapshot.forEach((childSnapshot) => {
console.log(childSnapshot.val());
});
}
First you are not using a userID, that's a random id generated using push() in your database. Therefore you need to use forEach() to access the data.
Check the guide:
https://firebase.google.com/docs/database/web/read-and-write
you dont exactly read data from firebase.
You should create a handle, which you did, a in your case
and then on that handle you register value event listener the code below is from official docs
ref.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
// ...
});
});
in your case you shloud just to
a.on("value",list=>{list.forEach(...)})
also you can subscribe for future child_added/removed/updated events
here are the docs
I get the user id's which is not contains a specific word. I need to update user status.
var primeusers = [];
var komence= firebase.database().ref();
function thisclick() {
komence.child('Buyers').on("value", function(snapshot) {
snapshot.forEach(function(data) {
if(!data.val().Nealdi.includes("GPA")) {
primeusers.push(data.key);
}
});
console.log(primeusers);
});
}
I can get the user id's.But I can't update their status.
//Update statatus to user under on "Users".
var vipata = firebase.database().ref();
vipata.child("Users").child(`primeusers`).once('value', function (snapshot) {
snapshot.forEach(function(child) {
child.ref.update({Minivip: "NO"});
child.ref.update({VIP: "NO"});
});
});
Database structure.
|-Buyers
|--Userid
|---Nealdi
|-Users
|--Userid
|---Minivip
|---VIP
I'll suppose you forgot the child "primeusers" in the structure schema shown. Try that:
var vipata = firebase.database().ref("Users");
vipata.child(`primeusers`).once('value', function (snapshot) {
snapshot.val().forEach(function(child) {
child.ref.update({Minivip: "NO"});
child.ref.update({VIP: "NO"});
});
});
Note here you are doing an update for each child. You can upgrade that by updating your object in your client side, and then update the entire object in once (it will be more beneficial for you). (I can link you an example if you want one).
This is my own firebase structure.
I want to get the particular data in firebase, for example: win. I get an error message for it. I have no idea to handle those particular id that create with firebase.
This my JavaScript code. When I run the program,the browser told me that the problem is in line 17.
You can listen for changes on child nodes, or you can fetch a node on demand. See documentation.
Listen for value events
var starCountRef = firebase.database().ref('posts/' + postId + '/starCount');
starCountRef.on('value', function(snapshot) {
updateStarCount(postElement, snapshot.val());
});
or read data on demand
var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) {
var username = (snapshot.val() && snapshot.val().username) || 'Anonymous';
// ...
});
I have the following db structure in firebase
I'm trying to grab data that belongs to a specific user id (uid). The documentation has the following example:
firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) {
var username = snapshot.val().username;
// ...
});
But how can I retrieve data from my example without knowing the unique key for each object?
Update:
I tried a new approach by adding the user id as the main key and each child object has it's own unique id.
Now the challenge is how to get the value of "title".
firebase.database().ref('/tasks/').orderByChild('uid').equalTo(userUID)
Well that is pretty straightforward. Then you can use it like this:
return firebase.database().ref('/tasks/').orderByChild('uid').equalTo(userUID).once('value').then(function(snapshot) {
var username = snapshot.val().username;
// ...
});
Of course you need to set userUID.
It is query with some filtering. More on Retrieve Data - Firebase doc
Edit: Solution for new challenge is:
var ref = firebase.database().ref('/tasks/' + userUID);
//I am doing a child based listener, but you can use .once('value')...
ref.on('child_added', function(data) {
//data.key will be like -KPmraap79lz41FpWqLI
addNewTaskView(data.key, data.val().title);
});
ref.on('child_changed', function(data) {
updateTaskView(data.key, data.val().title);
});
ref.on('child_removed', function(data) {
removeTaskView(data.key, data.val().title);
});
Note that this is just an example.
I have a firebase reference, where I pull data down for a specific custom index I created.
requestsRef
.orderByChild('systemgameindex')
.startAt(lastrequest.systemgameindex.toString())
.endAt(lastrequest.systemgameindex.toString() + '~')
.limitToFirst(customElem.dataops.limit + 1)
.on('child_added', function (snapshot) {
var request = snapshot.val() || {};
request.key = snapshot.key();
request.systemColor = customElem.getSystemColor(request.system);
request.description = customElem.truncateText(request.description, 65);
customElem.getUserProfile(request);
customElem.getCommentCount(request.key);
if (request.systemgameindex !== lastrequest.systemgameindex) { customElem.push('requests', request); };
customElem.removeSpinnerRoo();
});
Right before I make the call to firebase, I have a custom spinner I dislay with a function called addSpinnerRoo(), and when data is returned, I make a call to removeSpinnerRoo() to hide the spinner on the DOM.
It works beautifully when there's data to return from firebase, but if the firebase query brings back no results, the callback on child_added never gets fired, so I have a spinner still spinning on the DOM.
Is there a way to handle when there's no data returned within Firebase?
Any insight would be appreciated a lot. Thanks
After reading this from the documentation from here:
The callback function receives a DataSnapshot, which is a snapshot of the data. A snapshot is a picture of the data at a particular database reference at a single point in time. Calling val() on a snapshot returns the JavaScript object representation of the data. If no data exists at the reference's location, the snapshots value will be null.
I was able to do use "val" instead of "child_added" to actually have firebase still fire the callback for the ".on()" method. So my code now looks like this:
var data = snapshot.val();
if (data !== null && data !== undefined) {
var requests = _.map(data, function (val, key) {
val.key = key;
return val;
});
_.each(requests, function (request) {
request.systemColor = customElem.getSystemColor(request.system);
request.description = customElem.truncateText(request.description, 65);
customElem.getUserProfile(request);
customElem.getCommentCount(request.key);
customElem.push('requests', request);
});
}
customElem.removeSpinnerRoo();
And with that, I was able to get what I needed. If this helps anyone, great...