简体   繁体   中英

How To Export Firebase User ID To Another JS File?

I'm a beginner when it comes to NodeJS and Firebase through NodeJS. I'm trying to export the user ID of a user that's currently logged into my website, and export that user ID to another JavaScript file to be used there.

I've used the following code:

import { getAuth, onAuthStateChanged } from "firebase/auth";
const auth = getAuth();
onAuthStateChanged(auth, (user) => {
if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/firebase.User
    const uid = user.uid;
    // ...
} else {
    // User is signed out
    // ...
  }
});

from Firebase's documentation page for authentication (via Github) . I've used this code as a base to simply test out, but I've realized that any code I put in here and export, returns undefined.

Here is how my code is set up:
firebase.js File:

const { initializeApp } = require('firebase/app');
const { getFirestore, collection, getDocs } = require('firebase/firestore/lite');
const { getAuth, onAuthStateChanged } = require("firebase/auth");

const firebaseConfig = {
    apiKey: "xxxxxxxxxxxxxxx_xxxxxxxxx-xxxxxxxxxxxx",
    authDomain: "test-database-346d9.firebaseapp.com",
    projectId: "test-database-336c8",
    storageBucket: "test-database-346d9.appspot.com",
    messagingSenderId: "59s8107465422",
    appId: "X:xxxxxxxxxxxx:web:xxxxxxxxxxxxxxxxxxxxxx"
};

const app = initializeApp(firebaseConfig);
const db = getFirestore();

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
    if (user) {
        const uid = user.uid;
        module.exports = {uid};
    } 
    else {
        return;
    }
});

server.js File:

const user_id = require('./firebase');
console.log(user_id.uid);

I've tested this out with other code snippets and they work just fine. I just don't understand why this can't seem to work out.

Another attempt I tried was this:
firebase.js File:

async function call() {
    const querySnapshot = await getDocs(collection(db, "user-account"));
    querySnapshot.forEach((doc) => {
        const auth = getAuth();
        onAuthStateChanged(auth, (user) => {
            if(user) {
                if(user.email !== doc.data().email) {
                    return;
                }
                else {
                  let uid = user.uid;
                  module.exports = {uid};
                }
            }
        });
    });
}
call();

This also doesn't seem to work out. All the code above is doing is checking whether the user email matches the email inside the Firestore database as well. I don't understand why I keep getting undefined returned, however. Could someone please show me the correct way to achieve what I'm trying to do? Thank you.

I was having same problem when I started working with firebase + NodeJs, the google's documentation seems to be messy for me so I did a little of research and found a custom react hook for firebase which simplify integrating firebase on my nodeJs app very easily. This custom react hook is called: react-firebase-hooks You can find out more info here: https://www.npmjs.com/package/react-firebase-hooks Basically in your case the code that you need is this:

 //imports import { useAuthState } from 'react-firebase-hooks/auth'; import { getAuth } from 'firebase/auth'; const auth = getAuth(firebaseApp); const Page = () =>{ //react-firebase hook const [user, loading, error] = useAuthState(auth, options); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

and that's it, the user variable is an object that will contain all the informations that you'r looking for (id of user, email...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM