useUser: Listen for changes to logged in user
This commit is contained in:
parent
504053dde9
commit
344b06124f
|
@ -1,8 +1,15 @@
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { listenForLogin, User } from '../lib/firebase/users'
|
import { listenForLogin, listenForUser, User } from '../lib/firebase/users'
|
||||||
|
|
||||||
export const useUser = () => {
|
export const useUser = () => {
|
||||||
const [user, setUser] = useState<User | null>(null)
|
const [user, setUser] = useState<User | null>(null)
|
||||||
useEffect(() => listenForLogin(setUser), [])
|
useEffect(() => listenForLogin(setUser), [])
|
||||||
|
|
||||||
|
const userId = user?.id
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (userId) return listenForUser(userId, setUser)
|
||||||
|
}, [userId])
|
||||||
|
|
||||||
return user
|
return user
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,5 +1,11 @@
|
||||||
import { app } from './init'
|
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 { getAuth } from 'firebase/auth'
|
||||||
import { ref, getStorage, uploadBytes, getDownloadURL } from 'firebase/storage'
|
import { ref, getStorage, uploadBytes, getDownloadURL } from 'firebase/storage'
|
||||||
import {
|
import {
|
||||||
|
@ -33,6 +39,13 @@ export async function setUser(userId: string, user: User) {
|
||||||
await setDoc(doc(db, 'users', userId), 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'
|
const CACHED_USER_KEY = 'CACHED_USER_KEY'
|
||||||
export function listenForLogin(onUser: (_user: User | null) => void) {
|
export function listenForLogin(onUser: (_user: User | null) => void) {
|
||||||
// Immediately load any persisted user object from browser cache.
|
// Immediately load any persisted user object from browser cache.
|
||||||
|
|
Loading…
Reference in New Issue
Block a user