Stop flash of landing page when signed in and loading '/'

This commit is contained in:
jahooma 2021-12-16 21:37:36 -06:00
parent ef091f4359
commit 96791e11a5
3 changed files with 11 additions and 8 deletions

View File

@ -1,8 +1,8 @@
import { useEffect, useState } from 'react' 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 = () => { export const useUser = () => {
const [user, setUser] = useState<User | null | undefined>(undefined) const [user, setUser] = useState<User | null | undefined>(getCachedUser())
useEffect(() => listenForLogin(setUser), []) useEffect(() => listenForLogin(setUser), [])
const userId = user?.id const userId = user?.id

View File

@ -62,12 +62,6 @@ export function listenForUser(userId: string, setUser: (user: User) => void) {
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.
const cachedUser = localStorage.getItem(CACHED_USER_KEY)
if (cachedUser) {
onUser(JSON.parse(cachedUser))
}
return onAuthStateChanged(auth, async (user) => { return onAuthStateChanged(auth, async (user) => {
if (user) { if (user) {
let fetchedUser = await getUser(user.uid) 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() { export async function firebaseLogin() {
const provider = new GoogleAuthProvider() const provider = new GoogleAuthProvider()
signInWithPopup(auth, provider) signInWithPopup(auth, provider)

View File

@ -8,6 +8,8 @@ import Markets from './markets'
const Home: NextPage = () => { const Home: NextPage = () => {
const user = useUser() const user = useUser()
if (user === undefined) return <></>
return user ? <Markets /> : <Hero /> return user ? <Markets /> : <Hero />
} }