One of the questions I have been asked a lot about Firebase is:
How to get currently logged-in user data from Firebase Real-Time Database?
Let’s see how to do that in action.
I am assuming that you already know how to create a project in Firebase, add an appropriate Firebase Product SDKs, and initialization code to your project.
Recommended: Create A Firebase Project and Get Initialization Code
- Implement Firebase Authentication
- Add Logged In User Data
- Get Logged In User Data
- Protect User Data Using Security Rules
Implement Firebase Authentication
Add Firebase Auth SDK CDN to your HTML file.
<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-auth.js"></script>
Make sure to enable the Email/Password option under the Sign-in Method tab on the Firebase Authentication page.
Being lazy, I added an email and the password values hardcoded rather than getting them from HTML input elements.
var email = "raja@gmail.com"
var password = "pword1"
async function createNewAccount() {
try {
const user = await firebase.auth().createUserWithEmailAndPassword(email, password);
console.log(user.uid)
} catch (error) {
console.log(error.message)
}
}
When you invoke createNewAccount() on page load, a brand new Firebase account will be created on the Firebase Authentication page.
Recommended: FirebaseUI + Vue.js: Build A Complete Social Login Page
Get User Data Using Auth() Object
As soon as a new Firebase account is created, you’re in a logged-in state and user’s auth object is available inside onAuthStateChange() method.
firebase.auth().onAuthStateChanged(user => {<br> if(user) {
console.log(user.uid)<br> console.log(user.email)<br> }
})
User’s auth object will have some data about the logged-in user. If you want to add some additional information such as phone and address, you will need to store them into the real-time database.
Recommended
Learn Firebase Storage Quickly [Guide]
Add User Data To The Database
Once userAuth object becomes available, compose a user object with properties like name, phone, address, etc including uid and email from userAuth object.
Then, pass it to the writeUserData() function as an argument.
async function createNewAccount() {
try {
const userAuth = await firebase.auth().createUserWithEmailAndPassword(email, password);
var user = {
name: "Raja",
phone: "779797329",
address: "474 Mercer Drive",
uid: userAuth.uid,
email: userAuth.email
}
writeUserData(user)
} catch (error) {
console.log(error.message)
}
}
Top comments (1)
how to get data of other fields using uid?