Last active
December 2, 2021 10:57
-
-
Save ruaanvds/07d5c2ad7cdbe1c1c0b5e963ef77ddd2 to your computer and use it in GitHub Desktop.
Franco
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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