JS3
JS3

Reputation: 1829

How do I display the data of a logged in user?

const Account = (props) => {   const user = auth.currentUser;   if (user !== null) {
    const displayName = user.displayName;
    const email = user.email;

    const uid = user.uid;   }   return (
    <div>
       //display the user info here
    </div>   ); };

export default Account;

How do I display the data of a logged in user?

Upvotes: 0

Views: 99

Answers (2)

DIGI Byte
DIGI Byte

Reputation: 4174

If your auth Object is updated with onAuthStateChanged() then simply rendering the values into your script using the react variable's should work

return (
    <div>
       {user.uid}: {JSON.stringify(user)}
    </div>
    );

The above should print out the following

randomUserID: { "uid":"randomUserID", "email":"[email protected]"}

Upvotes: 1

Jabal Logian
Jabal Logian

Reputation: 2332

First, you have to define Firebase app and import Firebase Auth in your project. You can use this:

firebase.js

import firebase from 'firebase/app'
import 'firebase/auth'

const firebaseConfig = {
    apiKey: '...',
    authDomain: '...',
    databaseURL: '...',
    projectId: '...',
    storageBucket: '...',
    messagingSenderId: '...',
    appId: '...'
}

const firebaseApp = firebase.initializeApp(firebaseConfig)
const firebaseAuth = firebaseApp.auth()

export { firebaseAuth }

Then you can use the Firebase app you created, call the Firebase Auth using useEffect hook, and update the current user using useState hook like this:

YourComponent.js

import React, { useState, useEffect } from 'react'

const YourComponent = () => {
    const [ currentUser, setCurrentUser ] = useState('') // you can use '' or null

    const getCurrentUser = () => {
        firebaseAuth.onAuthStateChanged((user) => {
            if (user) {
                // you can print user here using console log if you want the detail info of the user
                const uid = user['uid']
                console.log('uid: ', uid)
                setCurrentUser(uid) // or you can use setCurrentUser(user) or setCurrentUser(user['uid']) depends on what data you want
            } else {
                console.log('uid: ', 'no uid')
            }
        })
    }

    useEffect(() => {
        getCurrentUser()
    }, [])

    return(
        <div>{currentUser}</div>
    )
}

export default YourComponent

Here is the official documentation https://firebase.google.com/docs/auth/web/start#set_an_authentication_state_observer_and_get_user_data

Upvotes: 1

Related Questions