Skip to content

Instantly share code, notes, and snippets.

@ruaanvds
Last active December 2, 2021 10:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruaanvds/07d5c2ad7cdbe1c1c0b5e963ef77ddd2 to your computer and use it in GitHub Desktop.
Save ruaanvds/07d5c2ad7cdbe1c1c0b5e963ef77ddd2 to your computer and use it in GitHub Desktop.
Franco
import { auth, firestore } from './firebase-config';
import { doc, collection, getDoc, setDoc, onSnapshot } from '@firebase/firestore';
import { useCallback, 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);
const getUserData = useCallback(async (user) => {
const documentRef = doc(firestore, 'users', user.uid);
const docSnap = await getDoc(documentRef);
if (docSnap.exists()) {
return onSnapshot(documentRef, (doc) => {
setUsername(doc.data().username);
});
} else {
const updatedUser = {
name: user.displayName,
email: user.email,
username: user.displayName,
};
setUsername(updatedUser);
await setDoc(doc(firestore, 'users', user.uid), updatedUser);
}
}, []);
useEffect(() => {
let unsubscribe;
if (user) unsubscribe = getUserData(user);
return unsubscribe;
}, [user]);
return { user, username, getUserData };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment