Skip to content

Instantly share code, notes, and snippets.

@gugazimmermann
Created July 19, 2020 23:41
Show Gist options
  • Select an option

  • Save gugazimmermann/7ec5bb71ef05aa45043ed6fd80ef3f45 to your computer and use it in GitHub Desktop.

Select an option

Save gugazimmermann/7ec5bb71ef05aa45043ed6fd80ef3f45 to your computer and use it in GitHub Desktop.
React Single-Player RPG - user Context
import React, {
useState, lazy, Suspense, useEffect, useContext,
} from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import CircularProgress from '@material-ui/core/CircularProgress';
import { Hub } from 'aws-amplify';
import { UserContext } from './context/UserContext';
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 [state, dispatch] = useContext(UserContext);
const [authInit, setAuthInit] = useState(true);
useEffect(() => {
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',
};
dispatch({ type: 'SET_USER', payload: formatUser });
} catch (err) {
dispatch({ type: 'UNSET_USER' });
}
setAuthInit(false);
}
checkAuth();
Hub.listen('auth', (data) => {
const { payload } = data;
if (payload.event === 'signOut') {
setAuthInit(false);
dispatch({ type: 'UNSET_USER' });
} else if (payload.event === 'signIn') {
checkAuth();
}
});
}, [dispatch]);
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>
{!state.user.id ? (
<Switch>
<Route path="/" render={() => <Auth />} />
</Switch>
) : (
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/home" component={Home} />
<Route component={NotFound} />
</Switch>
)}
</BrowserRouter>
</Suspense>
);
}
import React from 'react';
import ReactDOM from 'react-dom';
import CssBaseline from '@material-ui/core/CssBaseline';
import { ThemeProvider } from '@material-ui/core/styles';
import Amplify from 'aws-amplify';
import awsExports from './aws-exports';
import * as serviceWorker from './serviceWorker';
import UserProvider from './context/UserContext';
import App from './App';
import './index.css';
import theme from './theme';
Amplify.configure(awsExports);
ReactDOM.render(
<>
<ThemeProvider theme={theme}>
<CssBaseline />
<UserProvider>
<App />
</UserProvider>
</ThemeProvider>
</>,
document.getElementById('root'),
);
serviceWorker.register();
import React, { createContext, useReducer } from 'react';
const intialState = {
user: {
id: null,
name: '',
email: '',
avatar: '',
},
};
const UserReducer = (state, action) => {
switch (action.type) {
case 'SET_USER': {
return { ...state, user: action.payload };
}
case 'UNSET_USER': {
return { ...state, user: intialState };
}
default: {
return state;
}
}
};
export const UserContext = createContext({
state: intialState,
dispatch: () => null,
});
const UserProvider = ({ children }) => {
const [state, dispatch] = useReducer(UserReducer, intialState);
return (
<UserContext.Provider value={[state, dispatch]}>
{children}
</UserContext.Provider>
);
};
export default UserProvider;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment