Maarten de Wolf
Maarten de Wolf

Reputation: 182

How to fetch a single data value out of firebase database with reactjs

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)

Upvotes: 0

Views: 1517

Answers (1)

Frank van Puffelen
Frank van Puffelen

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:

  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(..).

Upvotes: 2

Related Questions