I'm trying to display the user's price that they entered in the database, but I'm getting "undefined' back instead of the value that was entered. I didn't get any errors in the console either. How can I fix this? I am using HTML, JavaScript, and CSS. I have provided a screenshot and my code.
Studio Dashboard JavaScript code:
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Initialize variables
const database = firebase.database();
const auth = firebase.auth();
//const auth = getAuth();
firebase.auth().onAuthStateChanged((user) => {
if (user) {
readData();
// ...
} else {
window.location.href = "login.html?error";
alert("No active user please sign or sign up.");
}
});
function readData() {
const user = firebase.auth().currentUser;
database.ref('/studiopick/studio/users/' + user.uid).get().then(snapshot => {
// Tab One Display
document.getElementById("studioName").innerText = snapshot.val().studioName;
document.getElementById("profile-name").innerText = snapshot.val().studioName;
document.getElementById("firstName").innerText = snapshot.val().firstName;
document.getElementById("lastName").innerText = snapshot.val().lastName;
document.getElementById("lastName").innerText = snapshot.val().lastName;
document.getElementById("email").innerText = snapshot.val().email;
document.getElementById("phoneNumber").innerText = snapshot.val().phoneNumber;
// Tab Two Display
document.getElementById("servicePrice").innerText = snapshot.val().numberInput;
}).catch(e => { console.log(e) })
}
function updatePrice() {
// Get data
numberInput = document.getElementById("numberInput").value;
const user = firebase.auth().currentUser;
// Enter database location
firebase
.database()
.ref('/studiopick/studio/users/' + user.uid + "/prices/roomA/serviceOne")
.update({
//studioName : studioName,
numberInput: numberInput,
});
}
You should use the on method instead of get
function readData() {
const user = firebase.auth().currentUser;
database.ref('/studiopick/studio/users/' + user.uid).on('value', (snapshot) => {
//Tab One Display
document.getElementById("studioName").innerText = snapshot.val().studioName;
document.getElementById("profile-name").innerText = snapshot.val().studioName;
document.getElementById("firstName").innerText = snapshot.val().firstName;
document.getElementById("lastName").innerText = snapshot.val().lastName;
document.getElementById("lastName").innerText = snapshot.val().lastName;
document.getElementById("email").innerText = snapshot.val().email;
document.getElementById("phoneNumber").innerText = snapshot.val().phoneNumber;
//Tab Two Display
document.getElementById("servicePrice").innerText = snapshot.val().numberInput;
}, (e) => { console.log(e) })
}
Related
I am using local storage to store username and password
I am getting null on active user after this line of code, I dont know why
console.log("I am the Active user: " + activeUser);
const menuChannelIcon = $(".menu-channel-icon");
const bellIcon = $(".bell-btn");
const uploadButtonIcon = $(".upload-btn");
const signInMainPageIcon = $(".signInMainPage");
const signUpMainPageIcon = $(".signUpMainPage");
const signOutMainPageIcon = $(".signOutMainPage");
const videoSectionMainPage = $(".video-section");
const signin = () => {
console.log("signin button clicked")
if (localStorage.getItem("formData")) {
// as long as you are getting items from the local storage... do..
JSON.parse(localStorage.getItem("formData")).forEach((data) => {
let x = $("#signEmail").val();
let z = $("#signinPassword").val();
if (data.email == x && data.pwd == z) {
isLogged = true;
activeUser = localStorage.getItem(email);
console.log("I am the Active user: " + activeUser);
menuChannelIcon.show();
bellIcon.show();
uploadButtonIcon.show();
signInMainPageIcon.hide();
signUpMainPageIcon.hide();
signOutMainPageIcon.show();
singIn_formContainer.hide();
videoSectionMainPage.show();
console.log("You are LOGGED");
}
});
}
};
Edit: email and pwd are set during signup
Answer posted by Barmar in the comments:
localStorage.getItem("email")
Alternative answer:
Shouldn't the active user be x when the email and password match something from formData? Why are you getting the active user from local storage?
Hey I am doing a sign up form, where every time the username textinput is changed, I look at my DB if it is available or not (to change the icon color of the text input to red or green).
const checkUsername = async () => {
// Get username from input
const username = usernameInput.current.props.value;
let isUsernameAvailable = false;
if (!isEmpty(username)) {
const { firebase } = props;
// Check if the username is available on the database and valid
isUsernameAvailable =
(await firebase.checkUsername(username)) && validateUsername(username);
}
setIsUsernameAvailable(isUsernameAvailable);
};
I have my own firebase rules to create a username only if not exists, but sometimes, when I write really fast the input and click on the submit button, a user with a not available username is created.
This is the submit function:
const signUp = async () => {
// Do not try to sign up again if the user is currently signing up
if (isLoading) return;
const { firebase, toast } = props;
const username = usernameInput.current.props.value;
const email = emailInput.current.props.value;
const password = passwordInput.current.props.value;
const repeatPassword = repeatPasswordInput.current.props.value;
// It is too important to check that the username is not taken
await checkUsername(username);
const formError = validateForm(username, email, password, repeatPassword);
// Do not sign up if the form is incorrect
if (formError) {
// Show error message
toast.current.show(formError, 3500);
return;
}
// Start loading
setIsLoading(true);
// Try to create the user with the email and password
firebase
.createUserWithEmailAndPassword(email, password)
.then((currentUser) => {
// Get the username from the input
const username = usernameInput.current.props.value;
// Create a user with this username and the current user uid in the db
firebase.createUserWithUsername(username, currentUser.user.uid);
})
.catch((err) => {
if (err.code !== "auth/too-many-request") {
// Convert error code to message
const message = firebase.parseError(err.code);
// Show error message
toast.current.show(message, 3500);
// Finish loading
setIsLoading(false);
}
});
/*
Pd: It has no sense to make a query if the username, email and password
are not valid. We avoid making extra queries.
*/
};
Any ideas?
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");
})
})
}
I am trying to write a firebase function which will check the the "user" and behave according to that on database write event. However when i query the database it returns null everytime and i didnt figure out what i am doing wrong. Any help is appreciated.
Thanks in advance.
My realtime database structure is like this:
ilk-projemiz-cd55baddclose
users
edRIPg8BcZU9YPbubp7HtQo7phl1
sayilar: 1532
status: "on"
hakan
sayilar: 5000
status: "waiting"
mehmet
sayilar: 7000
status: "on"
My firebase function file is this:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
exports.sayi = functions.database.ref("/users/{uid}/status").onWrite(event => {
const status = event.data.val();
var user = event.data.ref.parent.key;
if (status =="on") {
console.log(status);
const events = event.data.adminRef.child('users');
const query =events.orderByChild('status').equalTo('on').limitToFirst(2);
query.on("value", sorunsuz,sorunlu);
}
});
function sorunlu(error) {
console.log("Something went wrong.");
console.log(error);
}
function sorunsuz(data) {
console.log("11111");
var fruits = data.val();
console.log(fruits); //it returns null here
var keys = Object.keys(fruits);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if(key==user){
//console.log(fruits[key].sayilar);
console.log("aaa");
}else{
console.log("bbbb");
}
}
}
This line: const events = event.data.adminRef.child('users'); tries to access a users node under the status node. And I think what you wanted to do is access the users node under the root reference.
Use the Admin SDK instead:
const events = admin.database().child('users');
Update: the user variable is out of scope, so I suggest you move the sorunsuz() function to be inside the on() function:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sayi = functions.database.ref("/users/{uid}/status").onWrite(event => {
const status = event.data.val();
var user = event.data.ref.parent.key;
if (status =="on") {
console.log(status);
const events = admin.database().child('users');
const query =events.orderByChild('status').equalTo('on').limitToFirst(2);
query.on("value",
function(data) {
console.log("11111");
var fruits = data.val();
console.log(fruits); //it returns null here
var keys = Object.keys(fruits);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if(key==user){
//console.log(fruits[key].sayilar);
console.log("aaa");
}else{
console.log("bbbb");
}
}
}, sorunlu);
}
});
function sorunlu(error) {
console.log("Something went wrong.");
console.log(error);
}
you have to listen to users node
functions.database.ref("/users/{uid}/status"),
this path is not exist anywhere thats why you are getting null.
exports.sayi = functions.database.ref("/users").onWrite(event => {
const status = event.data.val(); //this data will be new
//Use above value to refer things
if (event.data.previous.exists()) {
//Update operation
}
});
How to get the value of Inmate_DOB from the below structure of Firebase Web API.
Please find the snap below :
I tried the below code is it right to handle, But I didn't retrieve the value.
GetInmate.Js
angular.module('starter.InMateIdContactDetailsController', ['firebase'])
.controller('InMateIdContactDetailsCtrl', function($scope,$rootScope,$filter,$ionicLoading,$state,$window, $cordovaSQLite,$cordovaCamera,$firebase,$firebaseAuth,$firebaseArray) {
var userId = firebase.auth().currentUser.uid;
var ref = firebase.database().ref().child("Tables/Inmate_Data");
$scope.InMatedata = $firebaseArray(ref);
if(!$scope.InMatedata){
alert('Records not found Auth!');
}else{
alert('Records found! Auth');
}
firebase.auth().onAuthStateChanged(function(user) {
if(user) {
var userID = user.uid;
firebase.database().ref('Tables/Inmate_Data/'+userID).once('value').then(snapshot => {
const userDOB = snapshot.val().Inmate_DOB;
alert(userDOB);
alert(test);
})
}
});
});
I think you are just missing a / in your original code after 'Tables/Inmate_Data'.
return firebase.database().ref('Tables/Inmate_Data/' + userId).once('value')
.then(function(snapshot) {
var Inmate_dob = snapshot.val().Inmate_DOB;
alert(Inmate_dob);
}
Instead of using firebase.auth().currentUser.uid, you might want to use onAuthStateChanged(), this way you can always be sure that the code inside the block will only be executed if the user is actually logged in otherwise firebase.auth().currentUser might return null. If you have made sure that this value is not null, then you can do something like this:
var userID = firebase.auth().currentUser.uid; //Current User UID
firebase.database().ref('Tables/Inmate_Data/'+userID).once('value').then(snapshot => {
const userDOB = snapshot.val().Inmate_DOB;
alert(userDOB);
});
To avoid getting null, you can put the above code inside onAuthStateChanged
firebase.auth().onAuthStateChanged(function(user) {
if(user) {
var userID = user.uid;
firebase.database().ref('Tables/Inmate_Data/'+userID).once('value').then(snapshot => {
const userDOB = snapshot.val().Inmate_DOB;
alert(userDOB);
});
}
});
If you want to retrieve the date of birth of all users, then you can do something like this:
firebase.database().ref('Tables/Inmate_Data').on('child_added', snapshot => {
firebase.database().ref(snapshot.key+'/Inmate_DOB').on('value', snap => {
const userDOB = snap.val();
alert(userDOB);
});
});