I would like to make use of react-router\'s onEnter
handler in order to prompt users to authenticate when entering a restricted route.
So far my route
After trying out a few of the above suggestions, I found the best way to track the state of your store with updates is to use React-Redux's useSelector
function which basically connects a functional component to the store.
import * as React from "react";
import {Redirect, Route, Switch} from "react-router";
import {Provider, useSelector} from "react-redux";
import { createBrowserHistory } from "history";
// Your imports
import {IApplicationState,} from "./store/store";
import {Login} from "./routes/login/login.component";
import {getToken} from "./store/helpers/httpHelpers";
function handleRedirect() {
if(!getToken()) {
return ;
}
}
const restricted = (Component: _ComponentType, isLoggedIn: boolean) => {
// Don't redirect here if there is a token in localStorage.
// This is happening when we are on a restricted route and the user
// refreshes & the isLoggedIn state hasn't been updated yet.
return !isLoggedIn ? (
() => handleRedirect()
) : () =>
};
const AuthenticateRoutes = () => {
const isLoggedIn = useSelector((state: IApplicationState) => state.auth.isLoggedIn);
return (
);
};
export function App() {
return (
<>
>
);
}