Retrieving user data from Firebase - javascript

I can't figure out what I'm doing wrong. The user name in Firebase is not being retrieved and updated.
This is my HTML:
<div class="header">
<div class="userPanel">
<div class="pic"></div>
<div class="welcome"><span>Welcome</span><h1 class="name" id="firstname">John</h1></div>
</div>
<div class="title"></div>
JS code:
firebase.auth().onAuthStateChanged((user) => {
if (user) {
console.log(user.uid);
var userRef = firebase.database().ref().child('Users')
var uid = user.uid;
var firstname = document.getElementById('firstname');
firebase.database().ref('Users/' + uid).on('value', function(snapshot){
var firstname.innerHTML = snapshot.val().Firstname;
});

Looks like the uid is undefined in the screenshot of your Firebase database. I'm guessing the user.uid you console.log is not undefined. What is output in your console?
Also, take out var in var firstname.innerHTML. You're not declaring a new variable called firstname.innerHTML.

Related

Format date and text data from API

I am working with Github API and I am displaying the data from users. When the date is displayed I want it to only have the date user.created_at with DD/MM/YY and not the whole hour. Also when the user has no Biography user.bio the data appears as null, and I want it to display the text 'The user has no bio'. I have not figured out the way to do both things so if you could help me I would very much appreciate it
Here below the code:
const APIURL = 'https://api.github.com/users/'
const main = document.getElementById('main')
const form = document.getElementById('form')
const search = document.getElementById('search')
async function getUser(username){
try{
const { data } = await axios(APIURL + username)
createUserCard(data)
getRepos(username)
}catch (err){
if(err.response.status == 404){
createErrorCard('No profile with this Username')
}
}
}
async function getRepos(username){
try{
const { data } = await axios(APIURL + username + '/repos?sort=created')
addReposToCard(data)
}catch (err){
createErrorCard('Problem Fetching Repos')
}
}
function createUserCard(user){
const cardHTML = `
<div class="card">
<div>
<img src="${user.avatar_url}" alt="${user.name}" class="avatar">
</div>
<div class="user-info">
<div class="header">
<h2>${user.name}</h2>
<p class="date">Joined ${user.created_at}</p>
</div>
<p>#${user.login}</p>
<p>${user.bio}</p>
<ul>
<div class="list">
<li>${user.followers} </li>
<li>${user.following} </li>
<li>${user.public_repos} </li>
</div>
<div class="list-names">
<strong>Followers</strong>
<strong>Following</strong>
<strong>Repos</strong>
</div>
</ul>
<div class="additional-data">
<p class="location"><img src="./img/location.svg" alt="Location" class="img" /> ${user.location} </p>
<img src="./img/link.svg" alt="Link" class="img" />${user.html_url}
</div>
<div id="repos"></div>
</div>
</div>`
main.innerHTML = cardHTML
}
function createErrorCard(msg){
const cardHTML = `
<div class="card">
<h1>${msg}</h1>
</div>
`
main.innerHTML = cardHTML
}
function addReposToCard(repos){
const reposEl = document.getElementById('repos')
repos
.slice(0, 5)
.forEach(repo => {
const repoEl = document.createElement('a')
repoEl.classList.add('repo')
repoEl.href = repo.html_url
repoEl.target = '_black'
repoEl.innerText = repo.name
reposEl.appendChild(repoEl)
})
}
form.addEventListener('submit', (e) => {
e.preventDefault()
const user = search.value
if(user){
getUser(user)
search.value = ''
}
})
in the case of user.bio you can use the ternary operator:
(conditional)?value when conditional true: value when conditional false
for example:
${(user.bio!="null")?user.bio:"The user has no bio"}
or
${(user.bio!=null)?user.bio:"The user has no bio"}
in the case of date github helps us giving us a formated string that we can cast to a date using new Date() and format it using Date.prototype.toLocaleString()
${(new Date(user.created_at)).toLocaleDateString()}
in this case is not needed to pass parameters to toLocaleDateString() but I encourage you to read about this function here

How to get value from dynamically generated <option> <select> express ejs

First of all I thank you for reading and making an attempt to my problem.
I dynamically rendered my {dropdown} but i was unable to get the selected value at my back-end.
on my form i am also getting photo and the name of suite is dynamically rendered.
Code below if i am doing something incorrect.
Lang - Javascript
FW - Express Js
Template - EJS
I have body-parse and set to true.
Issue i cannot get selected value to my back-end using POST request (undefined or null).
But if i use GET as the action & Request i do get the selected value.
Thank you again. If i am not clear please, i will explain clearly. I am newly NODE JS AND EXPRESS.
-Front-end
<form class="ui form" action="admin/uploadphoto" method="POST" enctype="multipart/form-data">
<h2 class=" ui dividing header" style="text-align: center;">Add Images to suites</h2>
<div class="two fields">
<div class="field">
<label>Add Suites Images</label>
<input name="suiteimage" type="file">
</div>
<div class="field">
<label>Suites*</label>
<select name="suiteselected" class="ui dropdown">
<% suites.forEach(function(suite) { %>
<option name = "suiteid" value="<%= suite.suite_name %>"><%= suite.suite_name %></option>
<% })%>
</select>
</div>
</div>
<input type="submit" class="ui button" tabindex="0" value="Save New Suite">
</form>
Back-end
const uuid = require("uuid/v4");
const { Pool } = require("pg");
const multer = require("multer");
// Insert photo and selected value from dropdown (options)
const PostPhoto = (req, res) => {
var suiteimage;
const suite_photo_id = uuid();
const {suiteselected} = req.body;
console.log( suiteselected + " --ID") //Here i am testing if selected valued is passed
// this is my multer function to config where i need to store my photo path
upload(req, res, err => {
suiteimage = req.file.path;
if (err) {
console.log(err);
} else {
console.log(suiteimage);
}
});
..... //my database query to save my post....
};
-route
router.post ('/uploadphoto', service.PostPhoto);
``
I have figured out the solution to this, body-parse should be required and extended true.
when having text and image as 1 form to be posted to the back-end make sure
Your image function (upload) is inside the req,res function or the values will be undefine or null.
if you need more explanation to comment.
//my post for image and text function
const PostPhoto = (req, res) => {
const suite_photo_id = uuid();
upload(req, res, function(err) {
const {suiteselected} = req.body;
console.log(req.file);
var imagePath = req.file.path.replace(/^public\//, '');
console.log( suiteselected + " --ID")
console.log(imagePath);
pool.query(
"INSERT INTO suite_photos (suite_photo_id,suite_photo,suite_id) VALUES($1,$2,$3)",
[suite_photo_id, imagePath,suiteselected],
(error, result) => {
if (error) {
throw error;
} else{
console.log(result);
res.redirect("/admin");
}
}
);
});
};
That's all that changed.
Thank you all!!!

Firebase database snapshot is not working?

I am trying to implement a simple search through firebase database. the logic is that
When A value is entered in the search box, go to database path of the entered value and get a snapshot value at the directory. for some reason, I have been stuck on this with the error listed below and I don't know what is causing it.
<form class="search" action="">
<input type="search" id="search-input" placeholder="Enter NSN number here..." required>
<button class="Init_search" id="findbutton">Search</button>
</form><br /><br />
the search result is displayed here
<div class="container"><br /><br />
<ul class="collapsible" data-collapsible="expandable" id="searchresult">
</ul>
</div>
this is my js code
document.getElementById("findbutton").addEventListener("click", function(e){
var FindNSN = document.getElementById('search-input').value;
firebase.auth().onAuthStateChanged((user) => {
if (user) {
database = firebase.database();
var uid = firebase.auth().currentUser.uid;
console.log(FindNSN);
var searchref = database.ref('/Businesses/' + uid + '/Inventory/' + FindNSN);
searchref.on('value', search, errData); // this is dashboard.js:363
}
})
})
function search(data){
var container = document.getElementById('searchresult');
var uid = firebase.auth().currentUser.uid;
container.innerHTML = '';
data.forEach(function(SearchSnap) {
var key = SearchSnap.key;
var Results = SearchSnap.val();
console.log(Results);
var ResultCard = `
<li>
<div class="collapsible-header"><i class="mdi-navigation-chevron-right"></i><a name="987"/>${Results.ProductName}</a></div>
<div class="collapsible-body"><p>${Results.ProductDescription}</p></div>
</li>
`;
container.innerHTML += ResultCard;
})
}
this is the error I keep getting
Uncaught (in promise) Error: Query.on failed: Second argument must be a valid function.
at A (firebase-database.js:44)
at U.g.gc (firebase-database.js:170)
at firebase.auth.onAuthStateChanged (dashboard.js:363)
at firebase-auth.js:202
at <anonymous>
A # firebase-database.js:44
g.gc # firebase-database.js:170
firebase.auth.onAuthStateChanged # dashboard.js:363
(anonymous) # firebase-auth.js:202
the error is saying second argument is not a valid function. i was able to narrow it down the search() but i cant see what makes the function invalid.
What am I doing wrong and How can I fix it?

Attendance Checking using firebase angular

I have a problem using firebase and angular for ionic. What i want to achieve is when users click list of dates then example 8 sept then user can see all attendace status of 8 sept.
after user click 8 sept. It show the list of user data and status of attendance in 8 sept.
this is my firebase database
So far i can display the list for every dates and user data. But the problem is my query display the status for all dates(8&9 Sept). How i can display the status for selected dates only?
this is my code that i have been working on.
Controller.js
childUsers.orderByValue().on('value', function(snapshot){
$timeout(function(){
var snapshotVal = snapshot.val();
$scope.users =snapshotVal;
console.log($scope.users);
});
});
Template
<div ng-repeat= "item in users">
<div class="list card" style="padding:1%;">
<div class="col-50" style="float:left;">
<h5>{{item.displayName}} - {{item.handphone}}</h5>
<h5>{{item.email}}</h5>
</div>
<div class="col-33" style="float:right; position: relative; ">
<div ng-if="item.status = 'true'">
<div class="ion-checkmark" style="display: flex; vertical-align: middle;"></div>
</div>
</div>
</div>
</div>
Any idea how to fix this? Thanks any help is appreciated.
I found the solution using nested snapshot here is my code
CONTROLLER
var rootRef = new Firebase('https://example-app.firebaseio.com/');
var childUsers = rootRef.child('users');
var childDate = rootRef.child('tanggal');
var rekapId = $stateParams.rekapId;
console.log(rekapId);
childDate.child(rekapId).child('tanggalBaca').once('value',function(snap){
$timeout(function() {
var snapshot= snap.val();
$scope.tanggal = snapshot;
console.log($scope.tanggal);
myAfterFunction();
});
})
function myAfterFunction(){
var dates = $scope.tanggal;
console.log(dates);
var rekapUsers = childUsers.on('value', function(snapshot){
snapshot.forEach(function(childSnapshot){
var key = childSnapshot.key();
console.log(key);
var childStatus = childUsers.child(key+'/status/'+dates);
childStatus.on('value',function(grandsnap){
var snapval =grandsnap.val();
$scope.statusbaca = snapval;
$scope.key = key;
console.log($scope.statusbaca);
console.log($scope.key);
})
})
var snapshotVal = snapshot.val();
$scope.users =snapshotVal;
console.log($scope.users);
})
}

Angularjs firebase array object always display false

Hi i having problem when i retrieve data from firebase in console.log($scope.statusbaca) it display 2 query true and false. but when it showing in the app it only display false. Sorry for my bad english. English is not my native language. Hope you understand my problem
App return false but console log display true and false
and this is my code
Template
<div ng-repeat= "item in users">
<div class="list card" style="padding:1%;">
<div class="col-50" style="float:left;">
<h5>{{item.displayName}} - {{item.handphone}}</h5>
<h5>{{item.email}}</h5>
</div>
<div class="col-33" style="float:right; position: relative;" ng-repeat = "datas in statusbaca">
<h5>{{datas}}</h5>
</div>
</div>
</div>
Controller
var rootRef = new Firebase('https://example-app.firebaseio.com/');
var childUsers = rootRef.child('users');
var childDate = rootRef.child('tanggal');
var rekapId = $stateParams.rekapId;
console.log(rekapId);
childDate.child(rekapId).child('tanggalBaca').once('value',function(snap){
$timeout(function() {
var snapshot= snap.val();
$scope.tanggal = snapshot;
console.log($scope.tanggal);
myAfterFunction();
});
})
function myAfterFunction(){
var dates = $scope.tanggal;
console.log(dates);
var rekapUsers = childUsers.on('value', function(snapshot){
snapshot.forEach(function(childSnapshot){
var key = childSnapshot.key();
console.log(key);
var childStatus = childUsers.child(key+'/status/'+dates);
childStatus.on('value',function(grandsnap){
var snapval =grandsnap.val();
$scope.statusbaca = snapval;
$scope.key = key;
console.log($scope.statusbaca);
console.log($scope.key);
})
})
var snapshotVal = snapshot.val();
$scope.users =snapshotVal;
console.log($scope.users);
})
}
Any idea what's wrong with my code and how to fix this? thanks
I'm not sure if this will fix it but your div elements are unbalanced.
You should add a ending div element like this,
<div class="col-33" style="float:right; position: relative;" ng-repeat = "datas in statusbaca">
<h5>{{datas}}</h5>
</div>
Also, I can't find some of the variables referenced by the HTML in the JavaScript and rather than having your
value output like this:
<h5>{{datas}}</h5>
you should have it like this:
<h5>{{datas.THE NAME OF YOUR KEY:VALUE PAIR}}</h5>
I can't test it since you're using firebase but, I would do quick run through with your code.

Categories