1

I am creating a custom hook in a react application that makes use of Firebase to auth and create a user document in the users collection. The hook checks if a user is logged in and then checks if the document in the users collection for that user exists. If the document does not exist, one is created, if the document exists I create a onSnapshot function to check for changes in the document. My problem is setting the username with useState when a new document is created. Can someone please assist. I am using Firebase V9.

Here is my hook:

import { auth, firestore } from './firebase-config';
import {
  doc,
  collection,
  getDoc,
  setDoc,
  onSnapshot,
} from '@firebase/firestore';
import { useEffect, useState } from 'react';
import { useAuthState } from 'react-firebase-hooks/auth';

// Custom hook to read  auth record and user profile doc
export function useUserData() {
  const [user] = useAuthState(auth);
  const [username, setUsername] = useState(null);

  useEffect(() => {
    let unsubscribe;

    if (user) {
      const documentRef = doc(firestore, 'users', user.uid);

      const getUserData = async () => {
        const docSnap = await getDoc(documentRef);
        if (docSnap.exists()) {
          unsubscribe = onSnapshot(documentRef, (doc) => {
            setUsername(doc.data().username);
          });
        } else {
          await setDoc(doc(firestore, 'users', user.uid), {
            name: user.displayName,
            email: user.email,
            username: user.displayName,
          });
          setUsername(docSnap.data().username);
        }
      };
      getUserData();
    } else {
      setUsername(null);
    }

    return unsubscribe;
  }, [user]);

  return { user, username };
}

0 Answers0