Privaterouting When Token In Local Storage [typescript]
If my login in successful, an authentication token is returned, which is stored in the local storage. Upon successful login, I want to go the a private route. I found this code Jav
Solution 1:
just replace fakeAuth.isAuthenticated by your saved token which you might save it also as a global state right? so, in general, it just a boolean prop to check if the user is successfully login or not depend on that situation the user will redirect either to the login page or the protected page
Solution 2:
This will go in your index.tsx file:
const token = localStorage.getItem('token');
constPrivateRoute = ({component, isAuthenticated, ...rest}: any) => {
constrouteComponent = (props: any) => (
isAuthenticated
? React.createElement(component, props)
: <Redirectto={{pathname: '/login'}}/>
);
return<Route {...rest} render={routeComponent}/>;
};
And use this in the browser router/switch:
<PrivateRoutepath='/panel'isAuthenticated={token}component={PrivateContainer}
/>
Post a Comment for "Privaterouting When Token In Local Storage [typescript]"