I am trying to use Firebase .on() method in order to check whenever a new account has been made in my realtime Firebase database. Now since I am encrypting this data in the Firebase Database, I would like to the first time the data from the firebase is loaded to decrypt it using a function that I made. Is it possible I could make something like a promise that will allow me to do this once the firebase loaded all the data in my variable?
var users2 = database.ref("users/").on("value", (snapshot) => {
const usersLst = snapshot.val();
users = usersLst
});
I would like to add something like this:
var users2 = database.ref("users/").on("value", (snapshot) => {
const usersLst = snapshot.val();
users = usersLst
}).then(() => {
console.log(decryptAccounts(users))
});
One important thing that I want to keep is the .on() function since that will allow me to constantly check whether someone has created a new account in the database. Does anyone have any ideas what is another approach I could use to achieve the same thing?
CodePudding user response:
You can just add the decryptAccounts() functions inside on() so everytime an update is received, you can run that function on that data.
var users2 = database.ref("users/").on("value", (snapshot) => {
const usersLst = snapshot.val();
// runs on new value fetched after every update
decryptAccounts(usersLst)
})
CodePudding user response:
You can store the ref in a variable to reuse it like the docs suggest.
const databaseRef = database.ref("users/");
// use databaseRef.get() with the correct path to your attribute you want to get
// Runs only once
databaseRef.get().then((snapshot) => {
// Decrypt function
});
// Listens to changes
var users2 = databaseRef .on("value", (snapshot) => {
const usersLst = snapshot.val();
users = usersLst
});
This first gets the values once and then you can decrypt them, when the values change the .on function will be fired again.
CodePudding user response:
The answer that I found with the help of Dharmaraj was that you can just do this:
database.ref("users/").on("value", (snapshot) => {
decryptAccounts(snapshot.val());
});
This would get the values from the database every time and decrypt them.
