Created
June 20, 2019 11:44
-
-
Save kartikpandey2/612a44fa1c339b645670af5e23335dd2 to your computer and use it in GitHub Desktop.
Trying to make Protected Route which will retrieve JWT token from localstorage and will make fetch call to the server to verify is token valid. If the token is valid Route is returned else user will be redirected to the login page.
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
import React, { Component, Fragment } from "react"; | |
import { Route, Redirect } from "react-router-dom"; | |
import Fetch from "./fetch"; | |
class PrivateRoute extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
isValidToken: false, | |
loading: true | |
}; | |
} | |
async componentDidMount() { | |
const options = { | |
method: "get" | |
}; | |
const response = await Fetch("/user/validjwt", options); | |
if (response) { | |
this.setState({ isValidToken: true}); | |
} else { | |
this.setState({ isValidToken: false }); | |
} | |
} | |
render() { | |
const { isValidToken } = this.state; | |
return isValidToken ? <Route {...rest} component={component} /> : <Redirect to="/login" />; | |
} | |
} | |
export default PrivateRoute; |
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
import React from "react"; | |
import { Switch } from "react-router-dom"; | |
import { PrivateRoute } from "./utils"; | |
import { Kyc, Wallet } from "./components/Account"; | |
import { CreateBooking, UserDetails } from "./components/Booking"; | |
import { Pay, PaymentLink } from "./components/Payments"; | |
const Routes = () => { | |
return ( | |
<Switch> | |
{/* {Account Routes} */} | |
<PrivateRoute exact path="/account/kyc" component={Kyc} /> | |
<PrivateRoute exact path="/account/wallet" component={Wallet} /> | |
{/* {Booking Routes} */} | |
<PrivateRoute exact path="/booking/create" component={CreateBooking} /> | |
<PrivateRoute | |
exact | |
path="/booking/create/user_details" | |
component={UserDetails} | |
/> | |
{/* {Account Routes} */} | |
<PrivateRoute exact path="/payment/" component={Pay} /> | |
<PrivateRoute exact path="/payment/link/" component={PaymentLink} /> | |
</Switch> | |
); | |
}; | |
export default Routes; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment