How to remove data from firebase? - javascript

I am having trouble removing data from my database on Firebase. I am able to remove data but when I remove the data its removing all my users? I only wanted it to remove the user represented in the user ID.
My JS
function removeUser(userID){
var userRef = firebase.database().ref('users/');
// Returned no user found
//var userRef = firebase.database().ref('users/').child('userID');
// Returned reference child error
//var userRef = firebase.database().ref('users/').child(userID);
userRef.once('value', function(snapshot) {
if (snapshot.val() === null) {
alert("no user found");
}else{
userRef.ref.remove();
}
});
console.log('Remove Success');
}
document.getElementById('removeUserBtn').addEventListener('click', function(){
removeUser(userID);
});

You need to specify the full path to the child you are trying to remove:
var childUserRef = firebase.database().ref(`users/${userId}`)
and call the .remove() method as in : childUserRef.remove()
More details:
https://firebase.google.com/docs/reference/js/firebase.database.Reference

Related

Display user's data in an html tag after reading them from firebase for webapps

This is the structure of my database, every user is in a child with value as that of their user-id
This is the code i am using
var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/users/' + userId).child("userName").once('value').then(function(snapshot) {
var username = (snapshot.val() && snapshot.val().username) || 'Anonymous';
$("#name-tag").append(username);
});
I want the userName value and have to display it
First change the way you authenticate the user then create a proper reference to the database.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var userDBRef = firebase.database().ref().child("User Database").child(user.uid);
userDBRef.on("value", function(userDB){
$("#para-id").append(userDB.child("userName").val());
});
} else {
// No user is signed in.
console.log("no user!!!");
}
});
Try this code :
var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/users/' +
userId).child("userName").once('value').then(function(snapshot) {
var username = snapshot.val() ? snapshot.val().username) : 'Anonymous';
$("#name-tag").append(username);
});
If snapshot.val() return null then usename will be 'Anonymus'

Firebase user stored in localstorage doesn't work? (javascript)

I'm saving the user object in localstorage upon creation (to be sure i can use it later inside a custom function, outside the authStateChanged):
const promise = auth.createUserWithEmailAndPassword(email, pass);
promise.then(e => {
var user = firebase.auth().currentUser;
localStorage.setItem('fireUser', JSON.stringify(user));
user.sendEmailVerification();
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
});
then i'm retrieving it inside my custom function below, it works when used like user.uid but it gives error "user.delete is not a function" when used as user.delete(), why is that? the variable user looks like this in the localStorage:
my custom function:
var myTimer;
function validTimer(timerValid){
var user = JSON.parse(localStorage.getItem('fireUser'));
// var buser = firebase.auth().currentUser; <-- doesn't work here
myTimer = setInterval(function() {
timerValid++;
localStorage.setItem('fireTimer', timerValid);
if (timerValid == 22) {
// delete in database
var userId = user.uid;
var ref = firebase.database().ref().child('users');
ref.child(userId).once("value", function(snapshot){
if (snapshot.exists()){
database.ref("users/"+userId).remove();
}
});
// delete account
user.delete().then(function() { // this says user.delete is not a function
}).catch(function(error) {
});
}
}, 1000);
}
It’s stripped of its instance methods when you stringify and parse it back. The delete method is an instance method for a firebase user object. In this case your user, although it looks the same, is not a firebase user. It’s just a bare object.
Edit
For persisting the firebase user via the Client SDK, you want to use the firebase.auth().onAuthStateChanged() method. Shortly after your page reloads, this method will fire. Set it here. Straight from the web starting guide:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var providerData = user.providerData;
// ...
} else {
// User is signed out.
// ...
}
});

Write to two database refs simultaneously

I have a Firebase web app serving as a registration system. When a user registers for a course, the course data is added to their list of all registrations as part of the callback function. When the user registers, the newest class is duplicated in the list. On a page load, each course is only listed once.
Realtime Database Structure
{
courses: {
courseIdA: {
// course data
},
couseIdB ... {}
},
users: {
uid: {
regs: {
courseIdA: true
}
}
}
}
When a user registers, they are added to both the course ID as a member object and to their users object under their uid. The callback fires twice because I'm writing to the courses ref and the users ref. Is there a way to write to both simultaneously? Or do I need to come up with a better structure for the database?
Get classes, listen for changes
PDReg.prototype.getAllClasses = function() {
this.database = firebase.database()
var uid = firebase.auth().currentUser.uid;
var courses = [];
var today = new Date().toISOString();
this.classesRef = this.database.ref('courses');
this.userRef = this.database.ref('users/' + uid + "/regs");
var setClass = function(snapshot) {
var course = snapshot.val();
course.key = snapshot.key;
// check for the current user in a course
if(course.members) {
if(course.members.hasOwnProperty(uid)) {
// This callback fires twice when someone registers
this.buildUserClasses(course);
} else {
this.buildAllClasses(course)
}
} else {
this.buildAllClasses(course)
}
}.bind(this);
// listen for changes to the classes database, rebuild the UI
this.classesRef.orderByChild('start').startAt(today).on('child_added', setClass);
this.classesRef.on('child_changed', setClass);
};
Register
PDReg.prototype.register = function(e) {
// It's a form submit, don't reload the page
e.preventDefault();
var form = this.courseForm;
var classes = [];
var uid = firebase.auth().currentUser.uid;
for (var i=0; i<form.elements.length; i++) {
// build the object to submit and add to an array
}
for (var i=0; i<classes.length; i++) {
this.coursesRef = this.database.ref('courses/' + classes[i].id + '/members/' + uid);
// Write the member object to `courses` under the correct key
this.coursesRef.set({'code': classes[i]['code']}).then(function(classes) {
// write to the user ref
firebase.database().ref('users/' + uid + '/regs/' + id).set(true);
onSuccess(title);
document.getElementById('allCourses').removeChild(document.getElementById(id))
}, function(e) {
onFailure(e, title);
});
}
};

Firebase does multiple calls even with if/else statement JS

I am building an app with Vue and also Firebase. I am new to Firebase and i've some problems with it. I try to store names + emails in the database. What I want is to check first if the email is already in the database and if not, run another function that will store the name + email. If the email is stored in the database I would like to output an alert and cancel the submit.
So the check of the email in the database is going quite well, it will output an alert, and also I am able to retrieve the data. But where the problem lays is that when I enter an email that is not in the database. When I enter a new email (and name) it will check the database and return false but then right away does another call (I dont know why, that's the problem I guess) and it will return true, and the alert of already being there, at the same time. Then it will proceed to another function to store the data because that was the output of the first call (which was false).
My JS code:
checkForm() {
let app = this;
if (this.name == '' || this.emailadress == '') {
alert('You have to fill out the form');
} else {
app.getFirebase();
}
},
getFirebase() {
let app = this;
var ref = firebase.database().ref().child('/aanmeldingen/');
ref.on('value', function(snapshot) {
const array = [];
snapshot.forEach(function(childSnapshot) {
var checkEmail = childSnapshot.val().email;
array.push(checkEmail);
});
const res = array.includes(app.emailadress);
console.log(array);
console.log(res);
if(res) {
alert('You already have entered the giveaway');
} else if (res == false) {
app.store();
}
});
},
store() {
this.step_two = false;
this.active_two = false;
this.active_three = true;
this.step_three = true;
let app = this;
firebase.database().ref('/aanmeldingen/').push({
username: app.name,
email: app.emailadress,
});
}
Screenshot of console (entered Jane, not in the database)
You should be using once() instead of on(). on() leaves the listener attached, so when you push data in store() the listener fires again.

How to get only one element from an array (firebase database, nodejs)

If I use limitToLast(1), then I still get an object, with one key-value pair. To get the value, I use this code:
db.ref('/myarray').limitToLast(1).once('value').then(function(snapshot) {
var result = snapshot.val();
var lastElem;
var lastKey;
for(var i in result) {
lastElem= result[i];
lastKey = i;
break;
}
...
});
It works, but I think I do it wrong. But haven't found any better solution in the docs. How should I load only one element?
The database looks like this:
When using Firebase queries to get children, use the "child_added" event:
db.ref("/myarray")
.orderByKey() // order by chlidren's keys
.limitToLast(1) // only get the last child
.once("child_added", function(snapshot) {
var key = snapshot.key;
var val = snapshot.val();
...
});

Categories

Resources