I'm creating a simple website and i'cant use firebase realtime databases crud operations with currentUserId.
My auth system working good; i can signIn/signUp/signOut on database. And i can write data to firebase with getting inputs from form.
//GETTING DATA WITH FORM
// Listen for form submit
document.getElementById('form').addEventListener('submit', submitForm);
// Submit form
function submitForm(e){
e.preventDefault();
// Get values
var name = getInputVal('name');
var sets = getInputVal('sets');
var reps = getInputVal('reps');
var weights = getInputVal('weights');
// Write data
writeData(name, sets, reps, weights);
// Clear form
document.getElementById('form').reset();
}
// Function to get form values
function getInputVal(id){
return document.getElementById(id).value;
}
//CRUD OPERATIONS
// Reference
var DataRef = firebase.database().ref('users/' + 'exercises/');
// Write data to database
function writeData(name, sets, reps, weights){
var newDataRef = DataRef.push();
newDataRef.set({
name: name,
sets: sets,
reps: reps,
weights: weights,
});
}
I didn't want to start reading, updating and deleting until I solved this id problem.
So how to do CRUD operations with each users with id? What can i do?
Are you asking how to write data in a location that is specific to the current user? If so:
var currentUser = firebase.auth().currentUser;
var DataRef = firebase.database().ref('users/' + currentUser.uid + '/exercises/');
Note that this only works if the current user is guaranteed to be already signed in. If you can't guarantee that, put the above code in an auth state listener.
Related
This is the database structure i have i want to get logged in user data.
i want to make table of data: Columns: Date,Status
Also i want to make percentage piechart wheel by calculating success and failure rate. but not able to get data from firebase.
I tried this but not working. I'm able to log in log out successfully. I'm also able to add data in firebase only once per date.
I'm just not able to fetch and show in table.
Here's what i tried:
`
// Get the user's attendance records
firebase.database().ref("attendance").once("value", function(snapshot) {
// Get the attendance data
var attendanceData = snapshot.val();
var userId = firebase.auth().currentUser.uid;
// Display the attendance history
for (var email in attendanceData) {
var attendance = attendanceData[email][userId];
if (attendance) {
for (var date in attendance) {
var status = attendance[date].status;
var tr = document.createElement("tr");
tr.innerHTML = `<td>${date}</td><td>${status}</td>`;
attendanceHistoryTable.appendChild(tr);
}
}
}
});
If I understand correctly, you have a data structure like this:
attendance: {
user: {
"$uid": {
"$date": {
Status: "..."
}
}
}
}
And from this you want to show the status per date for the current user.
If that's indeed the use-case, you can do this with:
const userId = firebase.auth().currentUser.uid;
const attendanceRef = firebase.database().ref("attendance");
const userRef = attendanceRef.child("users").child(userId);
userRef.once("value", function(userSnapshot) {
userSnapshot.forEach((dateSnapshot) => {
const status = dateSnapshot.child("Status").val();
console.log(`User: ${userSnapshot.key}, Date: ${dateSnapshot.key}, Status: ${status}`);
... // TODO: add the data to the HTML as you're already doing
});
});
The main changes I made here:
This only loads the data for the current user, instead of for all users.
This code uses the built-in forEach operation of a DataSnapshot.
This code gives more meaningful names to the variables, so that it's easier to parse what is going on.
This code uses "Status" rather then status, since that's the key in your database screenshot too.
I am using the firebase realtime database to display information that users on my web app can submit. A submit page is in use where particular users submit info to my database, where (this is where i'm stuck) that info is displayed on the said persons profile page.
This is what the database looks like
This is what the submit form looks like
This is the submit JS
function writeUserData() {
var user = firebase.auth().currentUser;
var userDisplayName = user.displayName;
var userid = user.uid;
var getFieldID = document.getElementById('id_field').value;
var getFieldName = document.getElementById('name_field').value;
var getFieldDate = document.getElementById('dateField').value;
var getFieldTime = document.getElementById('timeField').value;
var getFieldDesc = document.getElementById('desc').value;
const db = firebase.database();
db.ref('teachers/' + getFieldID).push({
student_UID: userid,
student_displayName: userDisplayName,
teacher_ID: getFieldID,
teacher_name: getFieldName,
date: getFieldDate,
time: getFieldTime,
description: getFieldDesc
});
};
How do I then get that user data and display it on a particular page? I've had a look through most of the documentation on firebase for web and can't find anything.
Now with the DB, multiple submissions under the same 'id' can be submitted and created with the .push function. My issue is retrieving the data and being able to display all submissions under a particular child (eg test1, test 2) on the webpage.
Thanks for any help!
You'll want to save a copy of the reference.
const teacherRef = db.ref('teachers/' + getFieldID).push({
student_UID: userid,
student_displayName: userDisplayName,
teacher_ID: getFieldID,
teacher_name: getFieldName,
date: getFieldDate,
time: getFieldTime,
description: getFieldDesc
});
console.log('teacherRef key', teacherRef.key);
teacherRef.once('value', snapshot => {
const value = snapshot.val();
console.log('saved value', value);
})
I just want to get the stripe customer ID whenever a new payment method is added to my database.
I'm new to realtime databases and I just need some guidance.
var newPaymentMethodRef = functions.database.ref('/stripe_customers/{uid}/newPaymentMethod');
var stripe_customers = functions.database.ref('/stripe_customers/{uid}');
exports.newPaymentMethod = newPaymentMethodRef.onWrite(event => {
console.log("uid = ${uid}");
console.log("newPaymentMethod created");
});
I've tried
event.key
event.parent.key
event.ref("/stripe_customers/")
I'm obviously lost
If the Stripe customer ID is the value that is passed in the {uid} part if the call to the database, you can get it with:
exports.newPaymentMethod = newPaymentMethodRef.onWrite((change, context) => {
console.log(context.params.uid);
Also see the Firebase documentation on Realtime Database triggers.
So I am new to the Firebase database and what I like about it is that I don't have to build a whole backend for just storing some simple data. What I am trying to do is pushing data to an array that I like to recieve from firebase. Then after that I would like to check if the email that was filled in, is included in the data from the firebase database. But because it's firebase and it has multiple arrays, objects etc I don't know how to check that. So the flow is: User fills in data, Applications makes a call to the firebase db and the Application is retrieving the current data from firebase. Then the Application will check if the data that is inputed is already there, and if so, will throw an alert that the data is already in the database. If not, the data will be submitted.
Also, I am wondering if this is the right way to retrieve data from the database:
Main.js
function writeUserData() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
firebase.database().ref('/aanmeldingen/').push({
username: name,
email: email,
});
var dbRef = firebase.database().ref().child('/aanmeldingen/');
dbRef.on('value', snapshot => {
const snap = snapshot.val();
const array = [];
array.push(snap);
console.log(array);
const res = array.includes(email);
console.log(res);
console.log(email);
});
}
Output in console
As you can see this returns multiple data. The include function will check on the submitted emailadress. This returns false even I had inputted "info#webpack.com". How can I check the right data object? It has to check all objects under "0" and return in the console if the submitted emailadress is already there.
I haven't tested it yet but i hope you get the idea. Also this is not the most efficient way to do this.
function ifEmailExist(arr,email){
var _t = 0;
for(var x in arr){
for(var y in arr[x]){
if(arr[x][y].email){
if(arr[x][y] === email){
_t++;
}
}
}
}
return _t;
}
Usage:
if(ifEmailExist(arr,"info#webpack.com") > 0){
//do stuff
}
You should use child_added instead of value. Whenever a new node is added in database, child_added will trigger and then you can take action on the data.
var dbRef = firebase.database().ref().child('aanmeldingen');
dbRef.on('child_added', snapshot => {
var username = snapshot.val().username;
var email = snapshot.val().email;
console.log(username);
console.log(email);
});
In my firebase app when a new user signs up I add their initial data like displayname, emai , photourl to the database under the top level users node. This works fine.
Now when a user post a status, I want to upload the the post to top level statuses node where all user statuses are kept. And simultaneously I want to upload the post to current user's posts node i.e users/currentuser/posts.
I am following the methods shown on official firebase site here.
The problem is when I hit the post button nothing happens and no data is posted to the database
My function that gets invoked when the post button is clicked:
function postStatus(){
var ref = firebase.database().ref("allstatuses");
var user = firebase.auth().currentUser;
var newStatusRef = ref.push();
var newStatusKey = newStatusRef.key();
var statusData = {
status: postInput.val(),
likes: 0,
dislikes: 0
};
var updateUserStatus = {};
updateUserStatus["users/" + user.uid + "/" + newStatusKey] = statusData;
updateUserStatus["allstatuses/" + newStatusKey] = statusData;
if(user){
firebase.database().ref().update(updateUserStatus);
}else{
alert("please login");
}
}
What am I doing wrong?
According to the API reference link it is key not key()
Change this
var newStatusKey = newStatusRef.key();
to
var newStatusKey = newStatusRef.key;