Pass page props user to auth provider if present (#724)

* Pass page props user to auth provider if present

* Rename `user` -> `serverUser`

* Don't load from local storage if server told us a user
This commit is contained in:
Marshall Polaris 2022-08-08 22:42:52 -07:00 committed by GitHub
parent fd308151b3
commit 5649161348
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 9 deletions

View File

@ -1,4 +1,4 @@
import { createContext, useEffect } from 'react'
import { ReactNode, createContext, useEffect } from 'react'
import { User } from 'common/user'
import { onIdTokenChanged } from 'firebase/auth'
import {
@ -28,15 +28,20 @@ const ensureDeviceToken = () => {
return deviceToken
}
export const AuthContext = createContext<AuthUser>(null)
export function AuthProvider({ children }: any) {
const [authUser, setAuthUser] = useStateCheckEquality<AuthUser>(undefined)
export const AuthContext = createContext<AuthUser>(undefined)
export function AuthProvider(props: {
children: ReactNode
serverUser?: AuthUser
}) {
const { children, serverUser } = props
const [authUser, setAuthUser] = useStateCheckEquality<AuthUser>(serverUser)
useEffect(() => {
const cachedUser = localStorage.getItem(CACHED_USER_KEY)
setAuthUser(cachedUser && JSON.parse(cachedUser))
}, [setAuthUser])
if (serverUser === undefined) {
const cachedUser = localStorage.getItem(CACHED_USER_KEY)
setAuthUser(cachedUser && JSON.parse(cachedUser))
}
}, [setAuthUser, serverUser])
useEffect(() => {
return onIdTokenChanged(auth, async (fbUser) => {

View File

@ -79,7 +79,7 @@ function MyApp({ Component, pageProps }: AppProps) {
content="width=device-width, initial-scale=1, maximum-scale=1"
/>
</Head>
<AuthProvider>
<AuthProvider serverUser={pageProps.user}>
<QueryClientProvider client={queryClient}>
<Welcome {...pageProps} />
<Component {...pageProps} />