Created
July 19, 2020 22:49
-
-
Save gugazimmermann/5d8639235944945fc9a206ef2032ed1f to your computer and use it in GitHub Desktop.
React Single-Player RPG - amplify hub
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { | |
| useState, lazy, Suspense, useEffect, | |
| } from 'react'; | |
| import { BrowserRouter, Route, Switch } from 'react-router-dom'; | |
| import CircularProgress from '@material-ui/core/CircularProgress'; | |
| import { Hub } from 'aws-amplify'; | |
| import { currentUserInfo } from './utils/auth'; | |
| const Auth = lazy(() => import('./screens/Auth')); | |
| const Home = lazy(() => import('./screens/Home')); | |
| const NotFound = lazy(() => import('./screens/NotFound')); | |
| export default function App() { | |
| const [user, setUser] = useState(); | |
| const [authInit, setAuthInit] = useState(true); | |
| async function checkAuth() { | |
| try { | |
| const currentUser = await currentUserInfo(); | |
| /** | |
| * Icon made by Darius Dan from flaticon | |
| * https://www.flaticon.com/authors/darius-dan | |
| */ | |
| const formatUser = { | |
| id: currentUser.attributes.sub, | |
| name: currentUser.attributes.given_name, | |
| email: currentUser.attributes.email, | |
| avatar: 'axe.png', | |
| }; | |
| setUser(formatUser); | |
| } catch (err) { | |
| console.log(err.message); | |
| } | |
| setAuthInit(false); | |
| } | |
| useEffect(() => { | |
| checkAuth(); | |
| Hub.listen('auth', (data) => { | |
| const { payload } = data; | |
| if (payload.event === 'signOut') { | |
| setAuthInit(false); | |
| setUser(); | |
| } else if (payload.event === 'signIn') { | |
| checkAuth(); | |
| } | |
| }); | |
| }, []); | |
| function Loading() { | |
| const lStyle = { | |
| display: 'flex', | |
| justifyContent: 'center', | |
| alignItems: 'center', | |
| }; | |
| return ( | |
| <main style={lStyle}> | |
| <CircularProgress /> | |
| </main> | |
| ); | |
| } | |
| if (authInit) { | |
| return <Loading />; | |
| } | |
| return ( | |
| <Suspense fallback={<Loading />}> | |
| <BrowserRouter> | |
| {!user ? ( | |
| <Switch> | |
| <Route path="/" render={() => <Auth />} /> | |
| </Switch> | |
| ) : ( | |
| <Switch> | |
| <Route exact path="/" component={Home} /> | |
| <Route exact path="/home" component={Home} /> | |
| <Route component={NotFound} /> | |
| </Switch> | |
| )} | |
| </BrowserRouter> | |
| </Suspense> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment