Standardize on useUser hook
This commit is contained in:
parent
7ec3da5504
commit
89a7bd65d2
|
@ -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}
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
@ -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 (
|
||||
|
|
Loading…
Reference in New Issue
Block a user