Retrieving current user data from firebase - javascript

I'm able to retrieve the data but it's only showing the data of the last user in the database. The users are listed by their uid. Below are the code and screenshot of the data from firebase. Help me out, guys!
var database = firebase.database().ref('users');
database.on("child_added", function(snapshot) {
var snapVal = snapshot.val();
displayName.innerHTML = snapVal.mUsername;
console.log(snapVal);
var badge = document.createElement('span');
badge.textContent = 'view details';
badge.setAttribute('class','badge');
var list = document.createElement('a');
list.textContent = snapVal.mUsername;
list.setAttribute('href', '#');
list.setAttribute('class', 'list-group-item');
patientList.appendChild(list);
list.appendChild(badge);
var userIcon = document.createElement('i');
userIcon.setAttribute('class','far fa-user');
list.insertBefore(userIcon, list.childNodes[0])
},
function (errorObject) {
console.log("The read failed: " + errorObject.code);
});

You should refer to the specific user's node to retrieve the information.
Your code should look like:
var userRef = firebase.database().ref(`users/${user_node_key}`); // user_node_key should be the node containing the user info.
You should be able to get the node key using the current user's object.
and then call once on the userRef if you just need to get the detail once or on if you need to listen all the changes on that user.
The code should look like:
userRef.once('value').then(function(snapshot) {
//use snapshot to get the users data
});

Related

Retrieve information from firebase doesn't work, key is not a function

I tried to solve it like this:
How to pull out data from firebase into html page - Stackoverflow
But I couldn't get it to work.
My html looks where I'll put the information from Firebase looks this in javascript:
var createTable = "<table><thead><tr id='keysRow'></tr></thead>";
var endHead = "<tbody><tr id='valuesRow'></tr></tbody></table>";
//More code that's connecting to each other and displays it in a div.
//F12 is showing me that this works.
Firebase.js:
var firebase = require('firebase');
firebase.initializeApp(config);
var v = firebase.database();
var users = firebase.database().ref("users");
users.orderByKey().once('child_added', function(snapshot){
snapshot.forEach(function(childsnapshot){
var key = childsnapshot.key(); <---------error
var data = childsnapshot.val();
$('#keysRow').append('<th>' + key + '</th>');
$('#valuesRow').append('<td>' + data + '</td>');
});
});
config is just the link to the firebase. I have no problem using the config to write in the firebase.
The error is telling me: "childsnapshot.key is not a function"
Also my firebase has 10 different values I need to get.
Change this:
var key = childsnapshot.key();
to this:
var key = childsnapshot.key;
check this link to see what has changed in Firebase 3.x: https://firebase.google.com/support/guides/firebase-web

Update data in firebase object

I want to update some data in an object in my firebase database, but have been unsuccessful so far.
I have been following the documentation to the point, but can't seem to get it right.. I'm fairly new to firebase, but this shouldn't be a huge problem.
My structure looks like this.
And this is how i have been trying to solve it:
userRef.on("value", function(snapshot) {
var user = firebase.auth().currentUser;
var key = user.uid;
var getUser = snapshot.val();
var userData = Object.keys(getUser);
var userKey = userData[0];
console.log(userKey);
var db = firebase.database();
var ref = db.ref("sofit-8ad52/profiles");
console.log(key);
var usersRef = ref.child(key);
usersRef.set({
userKey: {
Username: "TEST",
},
});
});
Would love some help on this one.

Create new spreadsheet with selected data from another sheet depending on the activeUser

first of all, this is the case:
I do have a masterdata sheet with lots of employee details (database). Column G contains email-adresses. I try to find a way to separate/select the lines for which the email-address matches the active user email-address. Without any opportunity for the user to change anything.
I tried different approaches with Query and IMPORTRANGE within the spreadsheet (e.g. =QUERY(IMPORTRANGE("101kbFw_DQGjmxhrw7BHK5-SM5IShkddre7GdqEhc2-U";"Data!A1:AC100"); "Select Col1,Col2,Col3,Col4 where Col7='Pascal Richter'"). But in this case the user would be able to change the name.
So I tried to build a webapp with the following functionalities:
the script identifies onOpen the activeUser
Button "send me data" starts the function createSSwithselectedData ()
the function createSSwithselectedData () creates a new spreadsheet
the function createSSwithselectedData () looks up the lines where the activeUser and the email in column g matches
the function createSSwithselectedData () transfers the identified data to the new spreadsheet
the activeUser gets an email with a link to the new spreadsheet
This is a dummy of the masterdata sheet.
Help is highly appreciated :)
// Log the email address of the active user
var email = Session.getActiveUser().getEmail();
Logger.log(email);
var DatabaseID = "101kbFw_DQGjmxhrw7BHK5-SM5IShkddre7GdqEhc2-U";
var Data = SpreadsheetApp.openById("101kbFw_DQGjmxhrw7BHK5-SM5IShkddre7GdqEhc2-U").getDataRange().getValues();
Logger.log(Data);
function doGet() {
var app = UiApp.createApplication();
// create a button and give it a click handler
var button = app.createButton("Send me data!").setId("button");
button.addClickHandler(app.createServerHandler("createSSwithselectedData"));
app.add(button);
return app;
}
function createSSwithselectedData(email) {
var app = UiApp.getActiveApplication();
app.getElementById("button").setText("Data is on the way");
return app;
var SheetTemplate = "1Z-ECGaRXaO8mEjTCx74z4sXOc_B7ZU81qfhtVJ3TAic";
var SheetName = "Jobgroup validation - ";
var newSheetName = SheetName + email ;
var folderId = "0B45D8-yA6A-HTWF1MjNhZW1VaXM"
var destination = DriveApp.getFolderById(folderId);
var copyId = DriveApp.getFileById(SheetTemplate).makeCopy(newSheetName, destination).getId();
var copySheet = SpreadsheetApp.openById(copyId);
// this is a new array to collect data
var target = new Array();
for(n=0;n<data.length;++n){ // iterate in the array, row by row
if (data[n][7]==email){ ; // if condition is true copy the whole row to target
target.push(data[n]); // copy the whole row
} //if
} //for
copySheet.getRange(1,10,target.length,target[0].length).setValues();
// Save and close the temporary document
copySheet.saveAndClose();
var url = copySheet.getUrl(); //DriveApp.getFileById(newFileId);
var link = "" + newSheetName + "";
var subject = "Jobgroup validation - " + email;
var body = "<p>You requested your team details. Please check the content.</p></br> " + link;
MailApp.sendEmail({to: email, subject: subject, htmlBody: body, name: alias, noReply: true});
}

Linking firebase accounts, JSON and images together

I have uploaded my image to the firebase database easily enough using this code:
uploadImageButton.addEventListener('change', function(e){
var file = e.target.files[0];
var storageRef = storage.ref('pictures/' + file.name)
var task = storageRef.put(file);
})
I was wondering how to link this to a particular user I have stored in my JSON, or to a user I have in my accounts?
When I sign up a user I want to be able to store an image and there auth account and retrieve them whenever I wish.
So far I can retrieve the relevant JSON, but not the auth account or images.
For that you just create a folder with the user UID and place the file inside that folder.
uploadImageButton.addEventListener('change', function(e){
var file = e.target.files[0];
var storageRef = storage.ref('pictures/' + UID +'/' + file.name)
var task = storageRef.put(file);
})
Here UID is the userid corresponding to the account.
use the folowing code to get the download url:
task.on('state_changed', function(snapshot){
var url = uploadTask.snapshot.downloadURL;
var updates = {};
updates['users/'+ UID +'/profile_image'] = url;
firebase.database().ref().update(updates);
}
Now you are setting the download url in profile_image property.

Titanium mobile - Uncaught Error: no such table

I am having a terrible time trying to figure out why I keep getting this error. I have searched this and other forums and no answer seems to be able to help so I will ask here.
I am trying to create a basic photo catalogue app for Android using Titanium. The catalogue info is strore in an sqlite database.
I can create the database OK - I can access some info from it in one window. When I then go to another window and try to get further info from the table it gives me the error:
Uncaught error: no such table: photos:, while compiling SELECT..........
See code below:
This is the first window that opens from app.js
The table shows up fine here - NO errors
// create var for the currentWindow
var currentWin = Ti.UI.currentWindow;
// set the data from the database to the array
//function setData() {
// create table view
var tableview = Ti.UI.createTableView({
});
//var db = Ti.Database.open('catalogue');
//db.remove();
var db = Ti.Database.install('catalogue.sqlite','photos');
var rows = db.execute('SELECT * FROM photos GROUP BY title');
// create the array
var dataArray = [];
while(rows.isValidRow()) {
var title = rows.fieldByName('title');
var id = rows.fieldByName('id');
dataArray.push({title:title, id:id, url:'catalogue_detail.js'});
rows.next();
}
tableview.setData(dataArray);
// add the tableView to the current window
currentWin.add(tableview);
tableview.addEventListener('click', function(e){
if (e.rowData.url)
{
var win = Ti.UI.createWindow({
id:e.rowData.id,
title:e.rowData.title,
url:e.rowData.url
});
win.open();
}
});
// call the setData function to attach the database results to the array
//setData();
I then open catalogue_detail.js from the above and I get the error
catalogue_detail.js
var win = Titanium.UI.currentWindow;
var id = win.id
var tableview = Titanium.UI.createTableView({
});
var db = Titanium.Database.open('catalogue.sqlite');//I have chanegd this to 'photos' and I get the same error
var sql = db.execute('SELECT title, location, photographer FROM photos where id="' + id + '"');
var title = sql.fieldByName('title');
var location = sql.fieldByName('location');
var photographer = sql.fieldByName('photographer');
// create the array
var dataArray = [];
while(sql.isValidRow()) {
var title = sql.fieldByName('title');
var location = sql.fieldByName('location');
var photographer = sql.fieldByName('photographer');
dataArray.push({title:title, location:location, photographer:photographer});
sql.next();
}
tableview.setData(dataArray);
win.add(tableview);
So the table in my database called 'photos' open in one window then I get the error trying to open the same database?
I have uninstalled the app, recreated the database, renamed tables etc but still the same error...
I am sure it is a simple thing I am missing but I am very confused!
Thanks for any assistance.
JC
Try absolute path: Ti.Database.open('catalogue.sqlite'); and Ti.Database.install('/catalogue.sqlite');.
Also remember about closing connection to database when you retrieve all data from query:
sql.close();
db.close();

Categories

Resources