Standardize on useUser hook

This commit is contained in:
Austin Chen 2021-12-09 15:37:26 -08:00
parent 7ec3da5504
commit 89a7bd65d2
4 changed files with 11 additions and 18 deletions

View File

@ -1,7 +1,7 @@
import { Popover } from '@headlessui/react'
import Link from 'next/link'
import { useEffect, useState } from 'react'
import { firebaseLogin, listenForLogin, User } from '../lib/firebase/users'
import { useUser } from '../hooks/use-user'
import { firebaseLogin } from '../lib/firebase/users'
const navigation = [
{
@ -12,12 +12,11 @@ const navigation = [
]
function SignInLink() {
const [user, setUser] = useState<User | null>(null)
useEffect(() => listenForLogin(setUser), [])
const user = useUser()
return (
<>
{user && user.id ? (
{user ? (
<Link href="/account">
<a className="text-base font-medium text-green-400 hover:text-gray-300">
{user.name}

View File

@ -3,10 +3,6 @@ import { listenForLogin, User } from '../lib/firebase/users'
export const useUser = () => {
const [user, setUser] = useState<User | null>(null)
useEffect(() => {
return listenForLogin(setUser)
}, [])
useEffect(() => listenForLogin(setUser), [])
return user
}

View File

@ -32,7 +32,7 @@ export async function setUser(userId: string, user: User) {
}
const CACHED_USER_KEY = 'CACHED_USER_KEY'
export function listenForLogin(onUser: (_user: User) => void) {
export function listenForLogin(onUser: (_user: User | null) => void) {
// Immediately load any persisted user object from browser cache.
const cachedUser = localStorage.getItem(CACHED_USER_KEY)
if (cachedUser) {
@ -63,9 +63,8 @@ export function listenForLogin(onUser: (_user: User) => void) {
// Note: Cap on localStorage size is ~5mb
localStorage.setItem(CACHED_USER_KEY, JSON.stringify(fetchedUser))
} else {
// User logged out; reset to the empty object
onUser({} as User)
localStorage.removeItem(CACHED_USER_KEY)
// User logged out; reset to null
onUser(null)
}
})
}

View File

@ -1,11 +1,10 @@
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
import { firebaseLogout, listenForLogin, User } from '../lib/firebase/users'
import { firebaseLogout } from '../lib/firebase/users'
import { Header } from '../components/header'
import { useUser } from '../hooks/use-user'
export default function Account() {
const [user, setUser] = useState<User | null>(null)
useEffect(() => listenForLogin(setUser), [])
const user = useUser()
const router = useRouter()
return (