Reputation: 182
Im working on a project trying to fetch a name of the current user that is logged in. When we create a user its getting added in the database with a unique id as row name.
Here you can see all the users that are registered but i only want the one that is logged in so i can pick the first and last name to say "Hello (bla) (bla)"
The code i have now it this :
import React from "react"
import { auth, database } from '../../handlers/Firebase'
export default function Dashboard() {
const user = auth.currentUser
const refUserInformation = database.ref('UserInformation/')
refUserInformation.on('value', function(data){
console.log(data.val())
})
return (
<div className="page-dashboard">
<div className="maxtext">
<p>userid: {user.uid}</p>
<p>Naam: </p>
</div>
</div>
)
}
Can just someone help me out with fetching the logged in user (so not a loop)
In summary, the problem is that I currently get all users back in my console log, but I only need the one that is logged in and on the appropriate dashboard. I would like to post this name (not with a loop but a single request)
Upvotes: 0
Views: 1517
Reputation: 598740
To get just the user with a given user_id
value, you will have to use a query:
const refUserInformation = database.ref('UserInformation/')
const currentUserQuery = refUserInformation.orderByChild('user_id').equalTo(user.uid);
currentUserQuery.on('value', function(snapshot){
snapshot.forEach((data) => {
console.log(data.val())
});
})
In general, I'd recommend storing user information with the UID as the key. That way:
To store the user under their UID use refUserInformation.child(user.uid).set(...)
instead of refUserInformation.push(..)
.
Upvotes: 2