From 8f11ed7947423da8c85ca6690a3352ad3afece08 Mon Sep 17 00:00:00 2001 From: Michael Fatemi Date: Sat, 10 Apr 2021 16:46:55 -0400 Subject: [PATCH] working authenticationwrapper --- src/components/AuthenticationContext.ts | 4 ++-- src/components/AuthenticationWrapper.tsx | 12 +++++++++--- src/components/Home.tsx | 19 +++++++++++++------ src/lib/getSessionId.ts | 2 +- 4 files changed, 25 insertions(+), 12 deletions(-) diff --git a/src/components/AuthenticationContext.ts b/src/components/AuthenticationContext.ts index 90c2050..82ca393 100644 --- a/src/components/AuthenticationContext.ts +++ b/src/components/AuthenticationContext.ts @@ -10,10 +10,10 @@ export type AuthState = { refreshAuthState: (() => void) | null; }; -const AuthContext = createContext({ +const Authentication = createContext({ isLoggedIn: false, user: null, refreshAuthState: null, }); -export default AuthContext; +export default Authentication; diff --git a/src/components/AuthenticationWrapper.tsx b/src/components/AuthenticationWrapper.tsx index 00aefd5..b8e09e1 100644 --- a/src/components/AuthenticationWrapper.tsx +++ b/src/components/AuthenticationWrapper.tsx @@ -1,6 +1,6 @@ import { useCallback, useEffect, useState } from 'react'; import { getMe } from '../api/api'; -import AuthContext, { AuthState } from './AuthenticationContext'; +import Authentication, { AuthState } from './AuthenticationContext'; export default function AuthenticationWrapper({ children, @@ -18,7 +18,11 @@ export default function AuthenticationWrapper({ const refreshAuthState = useCallback(() => { if (sessionId) { getMe().then((user) => { - setAuthState({ isLoggedIn: true, user, refreshAuthState }); + if (user) { + setAuthState({ isLoggedIn: true, user, refreshAuthState }); + } else { + setAuthState({ isLoggedIn: false, user: null, refreshAuthState }); + } }); } else { setAuthState({ isLoggedIn: false, user: null, refreshAuthState }); @@ -33,7 +37,9 @@ export default function AuthenticationWrapper({ return null; } else { return ( - {children} + + {children} + ); } } diff --git a/src/components/Home.tsx b/src/components/Home.tsx index 4b055bd..ca76d6f 100644 --- a/src/components/Home.tsx +++ b/src/components/Home.tsx @@ -1,7 +1,10 @@ -import { ION_AUTHORIZATION_ENDPOINT } from '../api/api'; import Button from '@material-ui/core/Button'; +import { useContext } from 'react'; +import { ION_AUTHORIZATION_ENDPOINT } from '../api/api'; +import AuthenticationContext from './AuthenticationContext'; export default function Home() { + const { user, isLoggedIn } = useContext(AuthenticationContext); return (

Home

- + {!isLoggedIn ? ( + + ) : ( + 'Hello ' + user?.first_name + '!' + )}