Skip to content Skip to sidebar Skip to footer

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');

const PrivateRoute = ({component, isAuthenticated, ...rest}: any) => {
    const routeComponent = (props: any) => (
        isAuthenticated
            ? React.createElement(component, props)
            : <Redirect to={{pathname: '/login'}}/>
    );
    return <Route {...rest} render={routeComponent}/>;
};

And use this in the browser router/switch:

<PrivateRoute
    path='/panel'
    isAuthenticated={token}
    component={PrivateContainer}
/>

Post a Comment for "PrivateRouting When Token In Local Storage [TypeScript]"