useUser: Listen for changes to logged in user

This commit is contained in:
jahooma 2021-12-14 18:45:13 -06:00
parent 504053dde9
commit 344b06124f
2 changed files with 22 additions and 2 deletions

View File

@ -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<User | null>(null)
useEffect(() => listenForLogin(setUser), [])
const userId = user?.id
useEffect(() => {
if (userId) return listenForUser(userId, setUser)
}, [userId])
return user
}

View File

@ -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.