Razvan Alex Razvan Alex - 1 month ago 13
Node.js Question

Firebase .on() method gets fired more than once

I'm making a custom firebase authentification method, so far I managed to make a form that collects users informations and send them with socket.io to the server and after that to the firebase if validation is fine. This is what I got so far, but when I start inserting in the firebase, the

console.log()
gets called more than once meaning that firebase tries to insert more than needed:

io.on("connection", socket => {
socket.on("register", user => {
console.log("Register") //gets called once, this is good!
let db = firebase.database();
let usersRef = db.ref("users").child(user.username);

firebase.database().ref("users").on("value", data => { //here we read from DB
console.log('Firebase begins here!') //this gets loged multiple times
let isValid = true; //simple var to check if validation is true/false
for (var el in data.val()) { //here we take user informations
if(data.val()[el]["name"]==user.username) { // check if username exists
console.log("Username already takken!") //gets fired more time
socket.emit("username")
isValid = false;
break;
}

if(data.val()[el]["email"]==user.email) {
console.log("Email is already takken!") //same story
socket.emit("email")
isValid = false;
break;
}
} //end of for in loop
console.log(isValid);
if(isValid) {
usersRef.set({
name: user.username,
email:user.email,
password: user.password,
balance: 0
})
}

} , errorObject => {console.log("The read failed: " + errorObject.code)})});});


The good part is that the
isValid
variable prevent insertion multiple times because after the first insertion
isValid
changes to false and it won't insert the datas. Anyway, this is not what I'm really looking for, the ideal is to use the .on() method only 1 time, not 5-6 times..

This is how my console.logs look like:

Register event!
Firebase begins here!
true
Firebase begins here!
Username already takken!
false
Register event!
Firebase begins here!
Username already takken!
false
Register event!
Firebase begins here!
Username already takken!
false
Register event!
Firebase begins here!
true
Firebase begins here!
Username already takken!
false
Firebase begins here!
Username already takken!
false
Firebase begins here!
Username already takken!
false
Firebase begins here!
Username already takken!
false


BIG UPDATE: The issue happens only when insertions starts, if there's already a username/email the same, it won't reapeat. Ty!

Answer

You should use ONCE method instead of ON.

Because every time socket.on("register" is called it register callback.

1st register user = 1 callback

2nd register user = 2 callback ( new callback + old callback from 1st)

3rd register user = 3 callback ( new callback + old callback from 1st + 2nd)

let's try