Tengo una app.js algo como esto
class App extends React.Component { render() { return ( <Routes> <Route path="/" element={ <PrivateRoute auth={{ isAuthenticated: AuthenticationResource.isLoggedIn() }} > {' '} <Navigate to="/dashboard" /> </PrivateRoute> } /> <Route path="/login" element={ <PublicRoute auth={{ isAuthenticated: AuthenticationResource.isLoggedIn() }} > {' '} <LoginPage /> </PublicRoute> } /> <Route path="/dashboard" element={ <PrivateRoute auth={{ isAuthenticated: AuthenticationResource.isLoggedIn() }} > {' '} <DashboardPage /> </PrivateRoute> } />y mi recurso de autenticación como este
import StorageFactory from './storage'; const AuthenticationResource = (() => { const storage = StorageFactory(); const getSessionId = function () { console.log('sessioncookie', storage.getItem()); return storage.getItem(); }; const removeSessionId = function () { return storage.removeItem(); }; return { isLoggedIn: () => typeof getSessionId() === 'string' && getSessionId().length > 0, }; })(); export default AuthenticationResource;He colocado una declaración de consola en la función getSessionId. Puedo ver los registros de la consola cuando la página se carga por primera vez. Pero cada vez que me muevo entre páginas usando navegar, no veo los registros de la consola, lo que infiero es que no se está llamando a isLoggedIn(). Por favor, ayúdame. Gracias de antemano
PS Así es como se definen el enrutamiento privado y el enrutamiento público
const PublicRoute = ({ auth: { isAuthenticated }, children }) => { return isAuthenticated ? <Navigate to="/dashboard" /> : children; }; const PrivateRoute = ({ auth: { isAuthenticated }, children }) => { return isAuthenticated === true ? children : <Navigate to="/login" />; };Se debe llamar a la función isLoggedIn cuando se accede a la ruta y no cuando se procesa el componente Route . Mover invocando la función en los componentes de protección de ruta.
Ejemplo:
const PublicRoute = ({ auth: { isAuthenticated }, children }) => { return isAuthenticated() // <-- invoke here ? <Navigate to="/dashboard" /> : children; }; const PrivateRoute = ({ auth: { isAuthenticated }, children }) => { return isAuthenticated() // <-- invoke here ? children : <Navigate to="/login" />; };...
<Routes> <Route path="/" element={ <PrivateRoute auth={{ isAuthenticated: AuthenticationResource.isLoggedIn // <-- pass reference here }} > <Navigate to="/dashboard" /> </PrivateRoute> } /> <Route path="/login" element={ <PublicRoute auth={{ isAuthenticated: AuthenticationResource.isLoggedIn // <-- pass reference here }} > <LoginPage /> </PublicRoute> } /> <Route path="/dashboard" element={ <PrivateRoute auth={{ isAuthenticated: AuthenticationResource.isLoggedIn // <-- pass reference here }} > <DashboardPage /> </PrivateRoute> } /> </Routes>