diff --git a/web/hooks/use-user.ts b/web/hooks/use-user.ts index ffa5abba..3499b230 100644 --- a/web/hooks/use-user.ts +++ b/web/hooks/use-user.ts @@ -1,8 +1,8 @@ import { useEffect, useState } from 'react' -import { listenForLogin, listenForUser, User } from '../lib/firebase/users' +import { getCachedUser, listenForLogin, listenForUser, User } from '../lib/firebase/users' export const useUser = () => { - const [user, setUser] = useState(undefined) + const [user, setUser] = useState(getCachedUser()) useEffect(() => listenForLogin(setUser), []) const userId = user?.id diff --git a/web/lib/firebase/users.ts b/web/lib/firebase/users.ts index b54df11d..a9536fb4 100644 --- a/web/lib/firebase/users.ts +++ b/web/lib/firebase/users.ts @@ -62,12 +62,6 @@ export function listenForUser(userId: string, setUser: (user: User) => void) { const CACHED_USER_KEY = 'CACHED_USER_KEY' 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) { - onUser(JSON.parse(cachedUser)) - } - return onAuthStateChanged(auth, async (user) => { if (user) { let fetchedUser = await getUser(user.uid) @@ -99,6 +93,13 @@ export function listenForLogin(onUser: (_user: User | null) => void) { }) } +export function getCachedUser() { + if (typeof window !== 'undefined') { + const cachedUser = localStorage.getItem(CACHED_USER_KEY) + return cachedUser ? (JSON.parse(cachedUser) as User) : undefined + } +} + export async function firebaseLogin() { const provider = new GoogleAuthProvider() signInWithPopup(auth, provider) diff --git a/web/pages/index.tsx b/web/pages/index.tsx index 7485a397..f264bb09 100644 --- a/web/pages/index.tsx +++ b/web/pages/index.tsx @@ -8,6 +8,8 @@ import Markets from './markets' const Home: NextPage = () => { const user = useUser() + + if (user === undefined) return <> return user ? : }