0

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.

User datas

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)

2
  • I would prefer to use firebase authentication instead it will save a lot of time, if you want to do it this way then you will have to store the user in a session, cookies or local storage. There are lot of tutorials on youtube based on what you are asking so you can check them out. Commented Nov 12, 2020 at 12:22
  • I get you but we allready use auth but we dont want to loop trought the users we just want to do a single fetch of 1 user and not get all users in once Commented Nov 12, 2020 at 13:14

1 Answer 1

2

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:

  1. Each UID can by definition occur only once in the database, since keys are unique under a parent node.
  2. Looking up the user info by their UID becomes simpler, since you won't need a query.

To store the user under their UID use refUserInformation.child(user.uid).set(...) instead of refUserInformation.push(..).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.