No result displaying firebase datas - javascript

I am a beginner in Javascript and Ionic, and I try to get my head around simply displaying datas from the database.
However I can't check my console while doing this for various reasons of device.
Anyway, here is the code I use to display the "description" of a user :
// Get a database reference to our posts
var descriptionRef = new Firebase("https://swapizapplication.firebaseio.com/accounts/-KOkwpzslw9NyUrTtvA7");
// Attach an asynchronous callback to read the data at our posts reference
descriptionRef.on("value", function(snapshot) {
var descriptionSnapshot = snapshot.child("displayDescription");
var description = descriptionSnapshot.val();
console.log(snapshot.val());
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
All I want is that when I write {{description}} on a html page linked to the controller that has that code, it displays the data of database for the user "-KOkwpzslw9NyUrTtvA7" at "displayDescription" (the name of one of the field in that user's database)
However it doesn't display the data. The page shows up, no particular error showing up, but the data just doesn't show up.
Here is how I made my controller (full view) :
.controller('AccountCtrl', function($scope, $state, $cordovaOauth) {
$scope.$on('$ionicView.enter', function() {
//Get logged in user credentials.
var user = firebase.auth().currentUser;
var name, email, photoUrl, provider;
console.log("User: " + JSON.stringify(user));
if (user != null) {
name = user.displayName;
email = user.email;
photoUrl = user.photoURL;
provider = user.provider;
description = user.displayDescription
}
//Set Profile Image.
$scope.profileImage = photoUrl;
//Set Profile Name.
$scope.profileName = name;
//Set Profile email.
profileEmail = email;
//Set provider.
provider = provider;
// Get a database reference to our posts
var descriptionRef = new Firebase("https://swapizapplication.firebaseio.com/accounts/-KOkwpzslw9NyUrTtvA7");
// Attach an asynchronous callback to read the data at our posts reference
descriptionRef.on("value", function(snapshot) {
var descriptionSnapshot = snapshot.child("displayDescription");
var description = descriptionSnapshot.val();
console.log(snapshot.val());
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
});
});
Any idea to help a NOOB ? :p
EDIT : Add the JSON of my database :
{
"-KOjv0LDdoWrc3uApvPi" : {
"dateCreated" : "Tue Aug 09 2016 11:29:18 GMT-0400 (EDT)",
"email" : "bla#blabla.net",
"provider" : "Facebook",
"userId" : "FMXlUQZth5aehQLT2TKZZJZdJBh2"
},
"-KOkwpzslw9NyUrTtvA7" : {
"dateCreated" : "Tue Aug 09 2016 16:16:52 GMT-0400 (EDT)",
"displayDescription" : "no description",
"email" : "blibli#blibli.com",
"provider" : "Facebook",
"userId" : "F9Z7YhSlmAQqOH5FVjBSV2CkYZG3"
}
}
EDIT 2 :
I considered going for another solution, it still doesn't want to work !
.controller('AccountCtrl', function($scope, $state, $cordovaOauth) {
$scope.$on('$ionicView.enter', function() {
//Get logged in user credentials.
var user = firebase.auth().currentUser;
var name, email, photoUrl, provider, description;
console.log("User: " + JSON.stringify(user));
if (user != null) {
name = user.displayName;
email = user.email;
photoUrl = user.photoURL;
provider = user.provider;
}
//Set Profile Image.
$scope.profileImage = photoUrl;
//Set Profile Name.
$scope.profileName = name;
//Set Profile email.
$scope.profileEmail = email;
//Set provider.
$scope.provider = provider;
var descriptionRef = firebase.database().ref('accounts/' + user + '/displayDescription/' );
descriptionRef.on('value', function(snapshot) {
description = snapshot.val();
$scope.description = description;
$scope.$apply();
});
});

To answer the main problem here, you're not exposing 'description' in the $scope, so the HTML template doesn't know that 'description' exists. So by calling {{description}}, you're probably getting an undefined, and that's why it isn't printing anything.
Then, referring to firebase. The statement firebase.auth().currentUser returns a firebase.User or null depending on whether you're logged in or not. A firebase.User does not contain a definition for provider. Instead, try using providerId or providerData. Also, a firebase.User neither contains a definition for displayDescription. That's an arbitrary key you defined in the user data as for /accounts/-KOkwpzslw9NyUrTtvA7/displayDescription.
If I'm not mistaken this should solve the problem:
.controller('AccountCtrl', function($scope, $state, $cordovaOauth) {
$scope.$on('$ionicView.enter', function() {
//Get logged in user credentials.
var user = firebase.auth().currentUser;
var name, email, photoUrl, provider, description;
console.log("User: " + JSON.stringify(user));
if (user != null) {
name = user.displayName;
email = user.email;
photoUrl = user.photoURL;
provider = user.providerId;
}
//Set Profile Image.
$scope.profileImage = photoUrl;
//Set Profile Name.
$scope.profileName = name;
//Set Profile email.
$scope.profileEmail = email;
//Set provider.
$scope.provider = provider;
// Get a database reference to our posts
var descriptionRef = new Firebase("https://swapizapplication.firebaseio.com/accounts/-KOkwpzslw9NyUrTtvA7");
// Attach an asynchronous callback to read the data at our posts reference
descriptionRef.on("value", function(snapshot) {
var descriptionSnapshot = snapshot.child("displayDescription");
description = descriptionSnapshot.val();
$scope.description = description;
console.log(snapshot.val());
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
});
});

Related

Firebase keep user logged in when navigating to other pages

I'm currently able to log in to my user account and successfully navigate to my dashboard while still logged in, but when I go to any other page, my login status is gone. Another issue is when updating my user's info, how can I write the function so that it's updating the info based on who's logged in? I have provided my code below. Thanks!
Edit profile JS:
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Initialize variables
const auth = firebase.auth()
auth.onAuthStateChanged( auth,user => {
var user = firebase.auth().currentUser;
if (user) {
alert("User active: ");
// User is signed in.
var email = user.email;
var uid = user.uid;
//Take user to a different or home page
window.location.href ="editprofile.html?id=" + uid;
} else {
alert("No active user please signup or sign in.");
window.location.href ="login.html?error";
}
});
var studioName, email, password, firstName, lastName, address, country, state, city, zip, phoneNumber;
function updateStu() {
//Get data
studioName = document.getElementById("studioName").value;
email = document.getElementById("email").value;
password = document.getElementById("password").value;
firstName = document.getElementById("firstName").value;
lastName = document.getElementById("lastName").value;
address = document.getElementById("address").value;
country = document.getElementById("country").value;
state = document.getElementById("state").value;
city = document.getElementById("city").value;
zip = document.getElementById("zip").value;
phoneNumber = document.getElementById("phoneNumber").value;
console.log(studioName, firstName, email);
firebase
.database()
.ref("/studiopick/studio/users" + studioName)
.update({
//studioName : studioName,
firstName : firstName,
lastName : lastName,
email : email,
password : password,
address : address,
country : country,
state : state,
city : city,
zip : zip,
phoneNumber : phoneNumber
});
document.getElementById("studioName").value ="";
document.getElementById("email").value ="";
document.getElementById("password").value ="";
document.getElementById("firstName").value ="";
document.getElementById("lastName").value ="";
document.getElementById("address").value ="";
document.getElementById("country").value ="";
document.getElementById("state").value ="";
document.getElementById("city").value ="";
document.getElementById("zip").value ="";
document.getElementById("phoneNumber").value ="";
alert("Data Updated");
};
For your first question:
You are using the auth.currentUser property instead of the user returned from onAuthStateChanged
As per The Docs:
import { getAuth, onAuthStateChanged } from "firebase/auth";
const auth = getAuth();
onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
const uid = user.uid;
// ...
} else {
// User is signed out
// ...
}
});
If user is returned successfully from onAuthStateChanged you can set the value of the returned user globally to access it throughout the app. Otherwise you can navigate to /login (or equivalent).
For your second question:
This depends on how you structured your database. It’s common practice to use the Firebase Auth Id as the users/ which can then be referenced from user.uid.
If you would like to keep record of who created or last edited a document you can keep fields that contain the users id.
Firestore also has security rules which leverage custom claims to secure the database CRUD operation.

Retrieving Firebase Child Value in Javascript

function sontinue() {
var user = firebase.auth().currentUser;
var uid = user.uid;
var adaRef = firebase.database().ref("User/" + uid);
if (adaRef.orderByChild("Role").equalTo("admin")) {
location.href = "DB.html";
} else {
location.href = "index.html";
}
}
I would like to link my "admin" account to DB.html and "user" account to index.html but i think i always failed in Retrieving the Child Value.
You're not retrieving the data from the server. Remember you need to call .once('value') to get your query and then iterate through the remaining code based onw hether their value is of admin or user. Firebase Docs has more explination I've amended your code and put it below
function sontinue() {
var user = firebase.auth().currentUser;
var uid = user.uid;
var adaRef = firebase.database().ref("User/" + uid).orderByChild("Role");
//you now need to retrieve the data
return adaRef.once('value').then((snapshot)=>{
return snapshot.forEach(snapshot=>{
if (snapshot.child("Role").val()==="admin") {
location.href = "DB.html";
} else {
location.href = "index.html";
}
return console.log("added");
})
})
}
If you just wanted to find out who was of the user type admin...i'd use this below...much more efficient.
function sontinue() {
var user = firebase.auth().currentUser;
var uid = user.uid;
var adaRef = firebase.database().ref("User/" + uid).orderByChild("Role").equalTo("admin");
//you now need to retrieve the data
return adaRef.once('value').then((snapshot)=>{
//you now have all the users that are just admins
return snapshot.forEach(snapshot=>{
location.href = "DB.html";
return console.log("added");
})
})
}

its given undefined. cant retrieve name from firebase

i want to get user data from firebase after login. when I get the name from database it is providing value as undefined.. why?
var user = firebase.auth().currentUser;
if(user != null ){
var email_id = user.email;
var uid = user.uid;
var name = user.userName;
var user = user;
document.getElementById("user_para").innerHTML = "Welcome User : " + email_id;
document.getElementById("user_para1").innerHTML = "Welcome User : " + uid;
document.getElementById("user_para2").innerHTML = "Welcome User : " + name;
}
Remember that firebase auth saves only the following data:
email: 'user#example.com',
emailVerified: false,
phoneNumber: '+11234567890',
password: 'secretPassword',
displayName: 'John Doe',
photoURL: 'http://www.example.com/12345678/photo.png',
disabled: false
So user.userName doesn't exist.
You can use displayName to save the username but if you really use it to save the name you can create a node called users in firebase realtime database where you could save the username based on UID, something like this:
users
->akdjf231dkeimdla
->username: jamesbond007
After you code could be:
var user = firebase.auth().currentUser;
if(user != null ){
var email_id = user.email;
var uid = user.uid;
var name = user.displayName;
document.getElementById("user_para").innerHTML = "Welcome User : " + email_id;
document.getElementById("user_para1").innerHTML = "Welcome User : " + uid;
document.getElementById("user_para2").innerHTML = "Welcome User : " + name;
firebase.database().ref('/users/' + uid).once('value').then(function(snapshot) {
//Here are reading the username from the database
var username = snapshot.val().username;
});
}
If you use firebase realtime database remember to add the firebase realtime database library.
For more information: https://firebase.google.com/docs/auth/admin/manage-users

how to automatic go to athor page, when success create account and set value at firebase database

i want make system, after success create an account and set value on Firebase database, it will go to the other page. i has set go to next page but, not set value into database. the think is, i want to make sure after create and set value to database and the system will move to another page.
var email = document.getElementById("email_field");
var password = document.getElementById("password_field");
firebase.auth().createUserWithEmailAndPassword(email.value, password.value).then(function(user)
{
var user = firebase.auth().currentUser;
if (firebase.auth().currentUser !== null)
console.log("user id: " + firebase.auth().currentUser.uid);
LogUser(user.uid);
console.log("user id: " + user.uid);
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error : " + errorCode+"message"+errorMessage);
if(err = null){
}
// ...
});
function LogUser(user){
firebase.database().ref('tbluser').child(user).set({
email: email,
test:"ha"
});
location.replace("signin.html")
}
}
Check out the article here on how to use Firebase Database callbacks.
Your code should look something like this:
firebase.database().ref('tbluser').child(user).set({
email: email,
test: "ha"
}, function(error) {
if (error) {
// it failed, do something here
} else {
// Data saved successfully!
location.replace("signin.html")
}
})
Good luck!

User ID not posting to Firebase

I'm trying to allow logged-in users post a title and description with their Google ID to Firebase, but the user ID is giving an undefined error in the console.
The error is only triggered when addIdea() function is called, when the form is posted. Form elements are simply ng-models for title and desc.
var app = angular.module("fluttrApp", ["firebase"]);
app.controller("fluttrCtrl", function($scope, $firebase) {
var ref = new Firebase("[forge].firebaseio.com/ideas");
var auth = new FirebaseSimpleLogin(ref, function(error, user) {
if (!user) {
auth.login('google', {
rememberMe: true
});
}
else {
console.log(user.displayName);
console.log(user.uid)
$scope.displayName = user.displayName;
$scope.uid = user.uid;
}
});
var sync = $firebase(ref);
$scope.ideas = sync.$asArray();
$scope.title = "";
$scope.desc = "";
$scope.addIdea = function(title, desc, uid) {
$scope.displayName = user.displayName;
$scope.uid = user.uid;
$scope.ideas.$add(
{
"title": title,
"desc": desc,
"user": uid
}
);
//The user id needs to be pulled and we need to post
//the idea id generated here to the user branch
$scope.title = '';
$scope.desc = '';
}
});
The object user is undefined because it is out of the scope of the $scope.addIdea() function.
It exists only in the callback of FirebaseSimpleLogin call.
Take a look at this example Monitoring Authentication for reference.

Categories