Created
August 17, 2019 11:06
-
-
Save faisalhmohd/2234e294877d2ac6a9c4929c9ebd1779 to your computer and use it in GitHub Desktop.
React Private Router Trial
This file contains 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
// THIS FILE IS ONLY FOR REFERENCE. | |
// IS NOT USED IN ANY PA | |
import React, { useReducer, useContext } from 'react'; | |
import { Redirect, RouteProps, Route } from 'react-router-dom'; | |
import config from '../config'; | |
import GoogleLogin from './GoogleLogin'; | |
const UserContext = React.createContext({}); | |
interface UserReducerActionObject { | |
type: string; | |
payload: any; | |
} | |
function userReducer(state: object, action: UserReducerActionObject) { | |
switch (action.type) { | |
case 'login': | |
return action.payload; | |
default: | |
return state; | |
} | |
} | |
const UserProvider: React.FC = ({ children }: any) => { | |
const contextValue = useReducer(userReducer, false); | |
return ( | |
<UserContext.Provider value={contextValue}> | |
{children} | |
</UserContext.Provider> | |
); | |
} | |
const useUser: Function = () => { | |
return useContext(UserContext); | |
} | |
function googleLoginOnFailure() { | |
console.log('Something Went Wrong!'); | |
} | |
const googleLoginOptions = { | |
clientId: config.googleClientId, | |
}; | |
const Login: React.FC = () => { | |
const [, userDispatch] = useUser() | |
function googleLoginOnSuccess(user: any) { | |
const userProfile = user.getBasicProfile(); | |
const userProfileData = { | |
id: userProfile.getId(), | |
name: userProfile.getName(), | |
avatarUrl: userProfile.getImageUrl(), | |
email: userProfile.getEmail() | |
}; | |
userDispatch({ | |
type: 'login', | |
payload: userProfileData | |
}); | |
return ( | |
<Redirect | |
to={{ | |
pathname: '/footage', | |
}} | |
/> | |
) | |
} | |
return ( | |
<div> | |
Login Page | |
<div> | |
<GoogleLogin | |
onSuccess={googleLoginOnSuccess} | |
onFailure={googleLoginOnFailure} | |
options={googleLoginOptions} | |
/> | |
</div> | |
</div> | |
) | |
} | |
interface PrivateRouteProps extends RouteProps { | |
component: any; | |
isSignedIn: boolean; | |
} | |
// @ts-ignore: Unreachable code error | |
const PrivateRoute: React.FC = ({ component: Component, ...rest }: PrivateRouteProps) => { | |
if (!Component) { | |
return null; | |
} | |
const [user] = useUser(); | |
console.log(user); | |
return ( | |
<Route | |
{...rest} | |
render={props => | |
user ? ( | |
<Component {...props} /> | |
) : | |
( | |
<Redirect | |
to={{ | |
pathname: '/login', | |
state: { from: props.location } | |
}} | |
/> | |
) | |
} | |
> | |
</Route> | |
); | |
}; | |
export default PrivateRoute; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment