Firebase get key value - javascript

It's easy to get value:
firebase_instance.limit(100).on("child_added", function(data) {
var value = data.val();
});
but how to get a key associated with that value?

Use key property
firebase_instance.limit(100).on("child_added", function(snap) {
var name = snap.key;
});
Documentation and examples here

Each of your Firebase .on(...) callbacks are going to be invoked with a Firebase DataSnapshot. To get the name for the location of that DataSnapshot, try using the name() method.
For example:
firebase_instance.limit(100).on("child_added", function(snap) {
var name = snap.name();
});

Related

How to retrieve data from Firebase using Javascript?

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.

Get firebase snapshot value outside of function

I want to send some generated data to the to a specific object child.
var user = firebase.auth().currentUser;
var key = user.uid;
// Set path for created user to be UID
var createProfileRef = firebase.database().ref("profiles/" + key);
var info;
createProfileRef.on("value", function(snapshot) {
var getData = snapshot.val();
info = Object.keys(getData)[0];
});
// Save Plan to logged inn user
var sendData = firebase.database().ref("profiles/" + key + "/" + info + sendDate);
savePlan(sendFat, sendProtein, sendCarbohydrate);
function savePlan(sendFat, sendProtein, sendCarbohydrate) {
var addData = sendData.push();
addData.set({
Macros_Fat: sendFat,
Macros_Protein: sendProtein,
Macros_Carbohydrate: sendCarbohydrate,
});
The only thing I need for this to work is to get the value of the variable "info". I just can't get it to get transferred outside of the function it is declared in...
If I place the function savePlan inside the snapshot it works, but it generated around 1000 keys constantly until I exit the application.
The easiest way you can do that is by setting the variable value in localStorage in the firebase function itself and get it outside the function from localStorage.
Here's the code:
// in firebase function
localStorage.setItem('info',info)
//outside the firebase function
localStorage.getItem('info');

Firebase3 listen for change event and get the old data value

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();
});

Retrieving data with firebase for Web

I am trying to retrieve data from a firebase database :
firebase.database().ref("/appointments").orderByChild("doctor").equalTo(doctorId).on("value", function(snapshot) {
var appointmentsData = snapshot.val();
for(var appointment in appointmentsData) {
if (!appointmentsData.hasOwnProperty(appointment)) continue;
var obj = appointmentsData.appointment;
}
});
If I console.log appointment or console.log appointmentsData, I get the correct value, but if I console.log appointmentsData.appointment, I get undefined.
Any idea how I can retrieve the properties and values from the object that firebase returns ?
You want to use Firebase's built in forEach function. It allows you to iterate through a snapshot and easily get the key and value of each property inside that object. It could be another object or a flat value.
firebase.database().ref("/appointments").orderByChild("doctor").equalTo(doctorId).on("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
// key
var key = childSnapshot.key;
// value, could be object
var childData = childSnapshot.val();
// Do what you want with these key/values here
...
});
});
Reference:
forEach, Firebase 3.0

Firebase - How to get list of objects without using AngularFire

Firebase - How to get list of objects without using AngularFire
I'm using typescript, angular2 and firebase.
I'm not using angularfire. I want to extract the data using their Api
My firebase url is /profiles
This is the list of profiles I'm looking to extract:
Thanks.
Use a simple value event and re-assign the array every time the value changes.
JSBin Demo.
var ref = new Firebase('https://so-demo.firebaseio-demo.com/items');
ref.on('value', (snap) => {
// snap.val() comes back as an object with keys
// these keys need to be come "private" properties
let data = snap.val();
let dataWithKeys = Object.keys(data).map((key) => {
var obj = data[key];
obj._key = key;
return obj;
});
console.log(dataWithKeys); // This is a synchronized array
});

Categories