Retrieve data from Firebase database in JavaScript - javascript

I am new to Firebase, and I am trying to figure out how to retrieve data from my Firebase database. I was able to add to it successfully based on a user's unique id (uid), but now getting data from it seems to be incredibly difficult. I want to grab the first name from the current user ('user' in the following code), but this JavaScript doesn't seem to be working:
var uid = user.uid
firebase.database().ref('users/' + uid).on('value', function(snapshot) {
this.first_name = snapshot.val().first_name;
});
As soon as I make the call to this.first_name, it gives me the following error:
FIREBASE WARNING: Exception was thrown by user callback. TypeError: Cannot set property 'first_name' of null.
In case it helps, my database is structured like this:
{
users: {
"uid1": {
first_name: "John"
},
"uid2": {
first_name: "Sue"
}
}
}

Use var first_name instead of this.first_name. It should work.
var uid = user.uid
firebase.database().ref('users/' + uid).on('value', function(snapshot) {
var first_name = snapshot.val().first_name;
});

The answer above is correct. but, i guess it's more readable if you use child in the query. Both should work.
firebase.database().ref('users').child(uid).on('value', function(snapshot) {
var first_name = snapshot.val().first_name;
});

Related

How i can read multiple child from database Firebase using DialogFlow?

I'm having trouble reading Firebase 'real database' data.
I created an intent with the parameter $nomeProf. When I pass a value and try to query in db a "Webhook call failed occurs.
Error: 500 Internal Server Error
Access to database is working, I just can't read the children.
I'm trying to get the email pass unique id in dialogflow consoles, example:
'qual o email do faria?', $nomeProf=faria.
'faria' and 'correa' are my unique like ID:
function getProfessorHandler (agent){
//let nomeProf = agent.parameters.nomeProf; #I need something like this?
return admin.database().ref("Professor").once('value').then((snapshot) => {
const value = snapshot.child("nomeProf").val();
const email = value.email;
if(value !== null){
agent.add(`O email é: ${email}`);
}
});
}
It sounds like you want to load a single child of Professor from the database, based on the agent.parameters.nomeProf value.
That'd be something like this:
return admin.database().ref("Professor").child(agent.parameters.nomeProf).once('value').then((snapshot) => {
const value = snapshot.val();
const email = value.email;
if(value !== null){
agent.add(`O email é: ${email}`);
}
});

Storing and retrieving data from Firebase comes back in different format

I'm trying to build this timetracker app where users can log how many hours per day they have worked. To give you an idea of what my app looks like, I put together a fiddle: https://jsfiddle.net/9vhfmjpy/
Here comes the tricky part. Whenever I try to store the data into a node in firebase by doing this:
submitHours() {
var uid = firebase.auth().currentUser.uid;
firebase
.database()
.ref("userhours/" + uid)
.set(this.rows)
.then(data => {
console.log(data);
});
},
it is turned into an object with an index value, as such:
userhours: {
userId: {
0: {
name: "username",
times: "time here"
}
}
}
Screenshot: https://prnt.sc/kpglr9
Having it formatted with that index makes it really to maintain. I can't effectively update/set/retrieve nodes.
I can use something like
loadUserHours() {
var userId = firebase.auth().currentUser.uid;
firebase.database().ref("userhours").once("value").then((data) => {
const allRows = [];
let obj = data.val();
for (let key in obj) {
allRows.push({
name: obj[key][0].name,
times: obj[key][0].times
})
}
console.log(allRows)
this.rows = allRows
})
},
to simply retrieve the values, but now... if there is more than 1 user in the userhours node I can't really update my node. If I try to use my submitHours() method now after updating the values for user #2 (https://prnt.sc/kpgqzq) it'll store the new information in a new node, in something that looks like this: https://prnt.sc/kpgqgs,
Can anyone help me out on how I can effectively store and retrieve data for my app?
Thanks a ton

How to retrive all the children from nested database in firebase using javascript

I am able to retrieve the child if it is present as data/ a, data/b. But I want to retrieve all the data which are present as data/key1/a, data/key1/b, data/key2/a, data/key2/b.
Now I am using the code as,
var rootRef = firebase.database().ref().child("notifications");
rootRef.on("child_added", snap => {
var uid = snap.child("uid").val();
});
This is giving me the data present in - notifications/key1/uid, notifications/key2/uid.
My database is made as notifications/key1/key1timestamp/uid, notifications/key2/key2timestamp/uid.
How do I edit my code to access that?
Try the following:
var db = firebase.database();
var ref1 = db.ref("notifications");
ref1.on("value", (snapshot) => {
snapshot.forEach((childSnapshot)=> {
childSnapshot.forEach((childrenSnapshot)=>{
let userId = childrenSnapshot.val().uid;
});
});
Assuming you have this database:
notifications
key1
key1timestamp
uid: id_here
key2
key2timestamp
uid:id_here
Since the snapshot is at notifications then loop twice to be able to retrieve the nested children

Firebase Web retrieve data

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.

In Firebase when using push() How do I get the unique ID and store in my database [duplicate]

This question already has answers here:
When utilizing the .push method can I write a copy of the id to the object?
(2 answers)
Closed 7 months ago.
I am pushing data in firebase, but i want to store unique id in my database also .
can somebody tell me,how to push the data with unique id.
i am trying like this
writeUserData() {
var key= ref.push().key();
var newData={
id: key,
websiteName: this.webname.value,
username: this.username.value,
password : this.password.value,
websiteLink : this.weblink.value
}
firebase.database().ref().push(newData);
}
error is "ReferenceError: ref is not defined"
You can get the key by using the function key() of any ref object
There are two ways to invoke push in Firebase's JavaScript SDK.
using push(newObject). This will generate a new push id and write the data at the location with that id.
using push(). This will generate a new push id and return a reference to the location with that id. This is a pure client-side
operation.
Knowing #2, you can easily get a new push id client-side with:
var newKey = ref.push().key();
You can then use this key in your multi-location update.
https://stackoverflow.com/a/36774761/2305342
If you invoke the Firebase push() method without arguments it is a
pure client-side operation.
var newRef = ref.push(); // this does *not* call the server
You can then add the key() of the new ref to your item:
var newItem = {
name: 'anauleau'
id: newRef.key()
};
And write the item to the new location:
newRef.set(newItem);
https://stackoverflow.com/a/34437786/2305342
in your case :
writeUserData() {
var myRef = firebase.database().ref().push();
var key = myRef.key();
var newData={
id: key,
Website_Name: this.web_name.value,
Username: this.username.value,
Password : this.password.value,
website_link : this.web_link.value
}
myRef.push(newData);
}
Firebase v3 Saving Data
function writeNewPost(uid, username, picture, title, body) {
// A post entry.
var postData = {
author: username,
uid: uid,
body: body,
title: title,
starCount: 0,
authorPic: picture
};
// Get a key for a new Post.
var newPostKey = firebase.database().ref().child('posts').push().key;
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['/posts/' + newPostKey] = postData;
updates['/user-posts/' + uid + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
}
You can get last inserted item id using Promise like this
let postRef = firebase.database().ref('/post');
postRef.push({ 'name': 'Test Value' })
.then(res => {
console.log(res.getKey()) // this will return you ID
})
.catch(error => console.log(error));
Try this . It worked for me
this.addressRef.push(addressObj).then(res => {
console.log("address key = " + res.key) ;
});
Here res.getKey() will not work but use res.key to get the latest push ID
It looks like now .push() always returns an Observable. When applied the solutions above I had the following error: "Type 'String' has no compatible call signatures".
That being said, I refer what did work in my case for this new version:
Type 'String' has no compatible call signatures
This worked for me:
var insertData = firebase.database().ref().push(newData);
var insertedKey = insertData.getKey(); // last inserted key
See Here: Saving data with firebase.

Categories

Resources