diff --git a/web/hooks/use-user.ts b/web/hooks/use-user.ts index 2512d5f3..a0954218 100644 --- a/web/hooks/use-user.ts +++ b/web/hooks/use-user.ts @@ -1,8 +1,15 @@ import { useEffect, useState } from 'react' -import { listenForLogin, User } from '../lib/firebase/users' +import { listenForLogin, listenForUser, User } from '../lib/firebase/users' export const useUser = () => { const [user, setUser] = useState(null) useEffect(() => listenForLogin(setUser), []) + + const userId = user?.id + + useEffect(() => { + if (userId) return listenForUser(userId, setUser) + }, [userId]) + return user } diff --git a/web/lib/firebase/users.ts b/web/lib/firebase/users.ts index 62a407a7..42739542 100644 --- a/web/lib/firebase/users.ts +++ b/web/lib/firebase/users.ts @@ -1,5 +1,11 @@ import { app } from './init' -import { getFirestore, doc, setDoc, getDoc } from 'firebase/firestore' +import { + getFirestore, + doc, + setDoc, + getDoc, + onSnapshot, +} from 'firebase/firestore' import { getAuth } from 'firebase/auth' import { ref, getStorage, uploadBytes, getDownloadURL } from 'firebase/storage' import { @@ -33,6 +39,13 @@ export async function setUser(userId: string, user: User) { await setDoc(doc(db, 'users', userId), user) } +export function listenForUser(userId: string, setUser: (user: User) => void) { + const userRef = doc(db, 'users', userId) + return onSnapshot(userRef, (userSnap) => { + setUser(userSnap.data() as User) + }) +} + const CACHED_USER_KEY = 'CACHED_USER_KEY' export function listenForLogin(onUser: (_user: User | null) => void) { // Immediately load any persisted user object from browser cache.