How to retrieve a specific data in Firebase Database? - javascript

After a user signed in his/her account, he/she will be ask what is his/her user role.
IMG 1: ask user role
After selecting a role, it will then be save in the database,
IMG 2: saved user role
So, how do we retrieve the specific data from Firebase database and then print it in the HTML?
IMG 3: show the user role
These are the codes I used in my .js
function app(user){
function updateMyStatus(e){
var myUpdate={};
myUpdate.email = user.email;
myUpdate.displayName = user.displayName;
myUpdate.status = document.getElementById("clientStatus").value;
fb.child(user.uid).set(myUpdate);
}
function receiveUpdate(received){
var data = received.val();
console.log( data );
document.getElementById('role').innerHTML= "";
}
document.getElementById('userName').innerHTML = user.displayName;
var fb = firebase.database().ref('Accounts');
document.getElementById("clientStatus")
.addEventListener("input",updateMyStatus);
}
and if the user has already a user role(status) as shown in the image 2, how do you hide the Dropbox that is shown in the image 1?

The below will get back your data from Firebase for that account. Then it is a matter of setting the values to their respective HTML elements.
fb.child(AccountId).on(‘value’, callbackFunction)
For reference: https://firebase.google.com/docs/database/web/read-and-write

function receiveUpdate(received){
var data = received.val();
console.log( data );
document.getElementById('role').innerHTML= "";
//hide the dropdown box
document.getElementById("clientStatus").style.display = "none";
}
document.getElementById("clientStatus").addEventListener("input",updateMyStatus);
//put this under your other event listener
fb.child('Accounts').on(‘value’, receiveUpdate);
This code will not work as written. I hope this helps give you a good idea.

Based on your current code, and based on my own understanding of the Firebase Realtime Database, these are the steps you need to take:
Register a listener to listen for changes to the database
To be more specific, you need to add a listener to the particular field that you are interested in in the database.
This listener should preferably not be inside any function.
This listener would check whether a role exists for your user in the database.
If yes, hide the input field and display user's details.
Else, display both the input field and the user's details.
As I have no experience using the Realtime Database (I have only used Cloud Firestore before), I am not very familiar with its syntax. But the link suggested by #Andre Kool and #thezachcannon in the previous post has examples of adding a listener to a particular database reference.
Hope that helped.

Related

Getting Firebase Realtime Database Value By Child

I'm developing an application that has a chat page.
I'm using Firebase realtime database and my chat structure like this:
I'm getting new messages as below:
fireBuddyChats = firebase.database().ref('/buddychats');
this.fireBuddyChats.child(this.currentUserId)
.child(this.buddy.uid)
.orderByKey()
.limitToLast(topMsgCount)
.on('value', (snapshot) => {
this.buddyMessages = [];
let temp = snapshot.val();
for(var tempKey in temp) {
this.buddyMessages.push(temp[tempKey]);
}
this.events.publish('newmessage');
}
I'm listening 'newmessage' event to show new message in chat page.
The problem is: While i chatting somebody, if another friend sends any message, database trigger (I mentioned above) runs and chat page shows another friend's messages. I think it shouldn't be triggered because the "this.buddy.uid" is different. What i'm missing? Is there any suggestion?
Maybe to prevent this you can add a conditional statement above to check if the user (the current user is talking to) actually has the uid of "this.buddy.uid". So maybe for the code you could possibly include somewhere:
if (socket.uid == this.buddy.uid).then
This should prevent other users from joining/adding themselves onto the real-time database conversation as it is checking if the user constantly.
Hopefully this helps.

In firebase (javascript), how can I get data for the currently logged in user?

I've spent a few days researching for the solution. I have found many answers that were quite helpful, but still I haven't been able to find a solution that fully resolved my problem. Basically all I want to do is to get current user's data (stored in firebase realtime database) and display them on the user's screen.
So far, I can display data for all the user. But how can I have it display data for only the current user? (How can I get the push key of only the current user?)
I'm not an experienced programmer (less than a year). Please use a language that is easy to understand.
I've gone through all the firebase documentation. Please don't just give me the copy of the documentation or the link to it.
Screenshot: Firebase realtime database
Screenshot: JavaScript function for retrieving current user's data
Additional JavaScript screenshot
User data is wherever you choose to store it--other than name, email, and a few other fields, the User object cannot actually store any other info. Therefore, you will need to decide where in the database you want to keep your extra data.
Assuming you choose to create a collection users with children named by uid, and you store the users' countries in those documents, the following will get you a specific user's data and you can use whatever fields you'd like from there:
let ref = database.ref('/users/' + currentUser.uid).once('value').then(function(snapshot) {
let userData = snapshot.val();
console.log(userData.country);
}
Here you go!
function showUser(){
var usref=firebase.database().ref("countries/"+uid);
//uid here is the unique code u gave to the specif user
usref.once('value', function(snapshot) {snapshot.forEach(function(childSnapshot) {
if((childSnapshot.key)=="country"){
var country = childSnapshot.val();
//use this variable here enter code here
window.alert(country);//just for checking!!!
}
if((childSnapshot.key)=="age"){
var name = childSnapshot.val();
//use this variable here
window.alert(name);//just for checking!!!
}
});
});
}
I hope this code works for you.

Best approach/design to web application?

I have been taking a Node.js course on Udemy and would like to apply some of the knowledge I have gained to create a simple web application. I would like to have a user register, which leads him to an admin panel, this part I already have.
This user (requester) can then refer users (invitees) to this website using a unique link. For example he would click a button to generate a unique hyperlink (my idea for this link was to be the http://websiteurl/userid of the requester who is sending the link).
The requester can then send this link through email to their friends to invite them to the website, once they click the link they are taken to a sign up form and when they fill in the form they are linked (added to an array under the original user).
How would I go about setting up this "session", as in make sure that the form that the invitees fill out is linked to the original requester? How can those forms be generated dynamically on the requester's hyperlink?
I'm not looking for the exact code to do this, but rather validation if my idea for the url is a good approach or if there are other approaches I should consider.
Thanks in advance!
Well, this would require you changing the schema for your database. A user will need to have a property like:
{
referred: []
}
The referred array should contain ids or some sort of reference to a user's referred users.
On the "/:userid" route, the form should submit to the route where a new user is created and have a parameter with the user ID. In this case, I am using query parameters.
So if a person were to visit /foo, they would get a form that would post to a URL like /new?userid=foo.
In that route, you can do something like this (assuming Express):
app.post("/new", (req, res) => {
const userID = req.query.userid;
const newUser = // create user normally
if(userID) {
// `userID` referred this user
const referrer = getUser(userID);
referrer.referred.push(newUser);
save(referrer);
}
});
The getUser function should returning the current user, and you should modify the referred property with the new user. This code was merely an outline and you should update the user in your database.
In a nutshell, a form should post to /new?userid=foo, and when creating a new user, if this parameter is present, you can update the database entry for the user id in the parameter with the id of the new user.

about local storage.getItem()

I'm a new learner for API, and I have a quesion about local storage. This is a code example from my javascript book:
if (Modernizr.localstorage) {
var txtUsername = document.getElementById('username');
var txtAnswer = document.getElementById('answer');
txtUsername.value = localStorage.getItem('username');
txtAnswer.value = localStorage.getItem('answer');
txtUsername.addEventListener('input', function () {
localStorage.setItem('username', txtUsername.value);
}, false);
txtAnswer.addEventListener('input', function () {
localStorage.setItem('answer', txtAnswer.value); }, false);
}
}
I want to ask why should we "localStorage.getItem()" part? Cause I think if user type their username, then we can get their names just from the variable "txtUsername" cause I thought it should be setItem first and then getItem. Thank you!
Local storage is used to store small amounts of data on the client side. What does your code ?!
For example: A user visited the site for the first time and complete the inputs, , the data stored in the local store. The user closed the browser. The next day he again went to the site to fill out the form again, and its data is already filled. Conveniently!
Also we can use local storage as js object
txtUsername.value = localStorage.getItem('username');
txtUsername.value = localStorage.username;
txtUsername.value = localStorage['username'];
The thing is, it works just as you said.
It's just, when person types data in the textbox he uses setItem - that what 'input' eventListener used for
Think of LocalStorage as of really light database that keeps data even when user closes the page
But since it can store data when page is closed, you want to show the content of it in the textbox - and that's why author uses 'getItem' on start

wordpress - how to take user data and send it in an email

I'm stuck and the plugin owner of wp-courseware don't wan't to offer assistance with this.
I am trying to grab the wordpress user data (email and country) and then put it into a file that will send this data dynamically.
I am using wp-courseware and I have found the following code and trying to intergrate the users details (mainly country into the code)
function WPCW_actions_users_moduleCompleted($userID, $unitID,
$unitParentData)
{
if (!$userID || !$unitID || !$unitParentData) {
return;
}
$userDetails = get_userdata($userID);
// Admin wants an email notification, and email address exists. Assumption
is that it's valid.
if ($unitParentData->email_complete_module_option_admin == 'send_email' &&
$unitParentData->course_to_email)
{
$adminSubject = __("Module Complete Notification - {USER_NAME} - Module
{MODULE_NUMBER}", 'wp_courseware');
$adminBody = __("Hi Trainer!
Just to let you know, {USER_NAME} has just completed 'Module {MODULE_NUMBER} - {MODULE_TITLE}'.
{SITE_NAME}
{SITE_URL}
", 'wp_courseware');
// Do email sending now
WPCW_email_sendEmail($unitParentData,
$userDetails, // User who's done the completion
$unitParentData->course_to_email,
$adminSubject, $adminBody);
}
// Check if admin wants user to have an email.
if ($unitParentData->email_complete_module_option == 'send_email')
{
WPCW_email_sendEmail($unitParentData,
$userDetails, // User who's done the completion
$userDetails->user_email,
$unitParentData->email_complete_module_subject, // Use subject template in the settings
$unitParentData->email_complete_module_body // Use body template in the settings
);
}
// Any additional admin-level notifications?
do_action("wpcw_user_completed_module_notification", $unitParentData,
$userDetails, $adminSubject, $adminBody);
}
This would depend on how you, or the plugin you're using, is saving the Country data to the database. Check out the wp_usermeta table and look for the key under which the country is saved. Or, since the function above is already grabbing all of the user's meta with $userDetails = get_userdata($userID);, you could print the $userDetails array and see what you have to work with.
Note how the email is grabbed by using $userDetails->user_email;. It will be similar to this, using that country meta_key instead.

Categories