Data not updating in Firebase and Ionic - javascript

I am new to Ionic / Firebase and I try to update fields via a form. Everything works, no error, all console log show up what needed but the data are not being updated in the database.
Here is my controller :
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
var nameInput = document.querySelector('#name');
var descriptionInput = document.querySelector('#description');
var saveButton = document.querySelector('#save');
saveButton.addEventListener("click", function() {
var name = nameInput.value;
var description = descriptionInput.value;
function writeUserData(name, description) {
firebase.database().ref('accounts/' + userId).set({
name: name,
description: description,
});
}
$state.go("tab.account");
});
Any idea ? Or maybe a better method to simply update firebase's database via a form when the user is logged in ?

Seems you didn't really don't know the real significance/uses of function yet about when to use it
Well it's because you wrap it inside writeUserData and which is you didn't event execute/call this function
Also function writeUserData isn't necessary in this situation
so remove function it
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
var nameInput = document.querySelector('#name');
var descriptionInput = document.querySelector('#description');
var saveButton = document.querySelector('#save');
receiveNewData();
function receiveNewData() {
// check if there's new data added
firebase.database().ref('accounts/' + userId).on('child_added', function(msg) {
var data = msg.val();
// your new data
console.log(data);
$state.go("tab.account");
});
}
saveButton.addEventListener("click", function() {
var name = nameInput.value;
var description = descriptionInput.value;
firebase.database().ref('accounts/' + userId).set({
name: name,
description: description,
});
});
You just transfer $state.go("tab.account"); to receiveNewData
Edited
To be able to catch the changes just call add child_added event listener inside 'accounts/' + userId
function receiveNewData() {
firebase.database().ref('accounts/' + userId).on('child_added', function(msg) {
var data = msg.val();
// your new data
console.log(data);
$state.go("tab.account");
});
}

Related

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

Uncaught TypeError: messagesRef.push is not a function

var firestore = firebase.firestore();
var messagesRef = firestore.collection("BookingData");
//listen for submit
document.getElementById('bookingForm').addEventListener('submit',submitForm);
function submitForm(e){
e.preventDefault();
//get values
var email = getInputVal('email');
var packageFields = getInputVal('packageFields');
var name = getInputVal('name');
var phone = getInputVal('phone');
var date = getInputVal('date');
//save messages
saveMessage(email, packageFields, name, phone, date);
}
// function to get form values
function getInputVal(id) {
return document.getElementById(id).value;
}
//save messages
function saveMessage(email, packageFields, name, phone, date) {
var newMessagesRef = messagesRef.push();
newMessagesRef.set({
email:email,
packageFields:packageFields,
name:name,
phone:phone,
date:date
});
}
But It Gives The Error :
Uncaught TypeError: messagesRef.push is not a function at saveMessage (bookingSubmit.js:48) at HTMLDivElement.submitForm (bookingSubmit.js:35) saveMessage # bookingSubmit.js:48 submitForm # bookingSubmit.js:35
Why is this happening and how can i solve it?
Please Check For Any Other Kind Of Errors.
And Make Sure That The Code Should Work As Expected. Its Constantly giving errors and now I am Fed up with it.
You are trying to add new document in the collection called BookingData.But while adding the data you are using a method push() associated with firebase Realtime Database.But the variable messageRef related with firebase firestore and there is no method called push() with firestore variable.
var firestore = firebase.firestore();
var messagesRef = firestore.collection("BookingData");
//listen for submit
document.getElementById('bookingForm').addEventListener('submit',submitForm);
function submitForm(e){
e.preventDefault();
//get values
var email = getInputVal('email');
var packageFields = getInputVal('packageFields');
var name = getInputVal('name');
var phone = getInputVal('phone');
var date = getInputVal('date');
}
// function to get form values
function getInputVal(id) {
return document.getElementById(id).value;
}
//save messages
function saveMessage(email, packageFields, name, phone, date) {
messageRef.add({
email:email,
packageFields:packageFields,
name:name,
phone:phone,
date:date
}).then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
}

Get the auto-generated id - Firebase

I'm trying to retrieve the id of the element that I inserted in the database with .key. However, it returns the user value instead of the auto-generated id.
How can I get the auto-generated id ?
var mainText = document.getElementById("main-text");
var emailText = document.getElementById("emailtxt");
var prenom = document.getElementById("prenomtxt");
var submitBtn = document.getElementById("submitBtn");
var heading = document.getElementById("heading");
var firebaseHeadingref = firebase.database().ref().child("titre");
firebaseHeadingref.on('value', function(datasnapchot){
heading.innerText = datasnapchot.val();
})
function submitClick(){
var firebaseref = firebase.database().ref();
var messageText = mainText.value;
var txtmail = emailText.value;
var prenomtxt = prenom.value;
if(messageText == "" || txtmail == "" || prenomtxt == ""){
alert("Tous les champs doivent être remplis");
return;
}
firebaseref.child("user").push().set({name : messageText, prenom:prenomtxt ,email : txtmail});
var f = firebase.database().ref().child("user").orderByChild("email").equalTo(txtmail);
// firebaseref.child("user").push({name: messageText, prenom:prenomtxt, email: txtmail}).then(pushed_user => {
//
// console.log(pushed_user.key);
//
// });
f.on("value", function(datasnapchot){
var id = datasnapchot.val();
console.log(id);
});
// location.reload();
}
There is a console notice:
It looks like you're using the development build of the Firebase J5 SDK. When deploying Firebase apps to production, it is advisable to only import the individual SDK components you intend to use. For the CON builds, these are available in the following manner (replace ‹PACKAGE> with the name of a component - 1.8. auth, database, etc):
https://www.gstatic.com/firebasejs/5.0.0/firebase-‹PACKAGE›.js
Try calling it like a function:
var id = datasnapchot.key();
When you push an element you can directly retrieve the auto generated ID without having to call a listener.
firebaseref.child("user").push({name: messageText, prenom:prenomtxt, email: txtmail}).then(pushed_user => {
console.log(pushed_user.key);
});
You can find another example here.
var newPostKey = firebaseref.child("user").push().set({name : messageText,prenom:prenomtxt ,email : txtmail}).key;
"newPostKey" will be your key
Try the following:
var ref = firebase.database().ref("users");
ref.push().on("value", function(snapshot) { snapshot.forEach(function(childSnapshot) {
var id = childSnapshot.key();
console.log(childSnapshot);
});
});
You need to loop using forEach and then you will be able to retrieve the push key using key()
This worked for me
var id = datasnapchot.key;
Use datasnapchot.key instead of datasnapchot.key()

Firebase data is "undefined" when it is not

I am trying to retrieve some data from my firebase database, but the value I get is "undefined".
This is how I save the data to the database:
var database = firebase.database();
database.ref().push({
mainArray: mainArray,
secondArray: secondArray,
listname: listName,
mainLanguage: mainLanguage,
secondLanguage: secondLanguage,
}, function(error) {
if (error){
stopLoader();
showSnackbar("An error has occured! Please try again later.");
}
This is how I read the data, but the value of listname is "undefined":
var database = firebase.database().ref().child('codes');
var codeInput = document.getElementById('mainSearch');
database.on('value', function(snapshot) {
if (!snapshot.hasChild(codeInput.value)) {
codeInput.value = "";
showSnackbar("A list with this code does not exist!<br><br>Please try another one.")
}
else {
var data = snapshot.val();
var listname = data.listname;
console.log(listname);
}
});
This is the value I get from the database:
This is how the data is structured in the database:
I changed my code to this and now it works perfectly. The problem was that i was trying to get the value from the wrong child. Thanks for your help and patience!
var database = firebase.database().ref().child('codes');
var codeInput = document.getElementById('mainSearch');
database.child(codeInput).on('value', function(snap) {
var data = snap.val();
var listName = data.listname;
var mainLanguage = data.mainLanguage;
var secondLanguage = data.secondLanguage;
var mainArray = data.mainArray;
var secondArray = data.secondArray;
});

Firebase custom query

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

Categories