Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

266
Vistas
How to stay on the protected route, after refreshing page. React router 5.2.0

I have public and protected routes, which implemented in the following logic

   useEffect(() => {
      checkIfAuthenticated(); //This function checks if the token is in localStorage
     // Initial state isAuthenticated = false
    }, []);
   const newHistory = useHistory()

   <Router history={newHistory}>
    {isAuthenticated ? (
      <Layout>
        <Switch>
          <Route
             exact
             path="/clients"
             component={Clients}
            />
          <Route
             exact
             path="/staff"
             component={Staff}
            />
          <Redirect to="/clients" />
        </Switch>
      </Layout>
       ) : (
      <>
       <Route path="/login" component={Login} />
       <Redirect to="/login" />
      </>)}
    </Router>

//store
checkIfAuthenticated() {
    const accessToken = localStorage.getItem("access_token");
    const refreshToken = localStorage.getItem("refresh_token");
    if (accessToken && refreshToken) {
      this.isAuthenticated = true;
    }
  }

The problem is when I refresh the page on the route /staff?page=1, the app initializes from scratch and I am redirected to the /clients route. Is there any way to handle this case? I.e when I refresh the private route, I should stay on the same page. Maybe I should save the current route to the localStorage?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You must use redux-persist library to keep the value of isAuthenticated variable in localStorage after refresh.

Something like this:

import { persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';

import userReducer from './userReducer';

const persistConfig = {
  key: 'user',
  storage,
  whitelist: ['access_token', 'refresh_token'],
};

const persistedReducer = persistReducer(persistConfig, userReducer);
about 4 years ago · Juan Pablo Isaza Denunciar

0

If you are sure about persistance of variables in localStorage check this as well:

const accessToken = localStorage.getItem("access_token");
const refreshToken = localStorage.getItem("refresh_token"); 
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
  if (accessToken && refreshToken) {
    setIsAuthenticated(true);
  }
}, [accessToken , refreshToken ]);

const newHistory = useHistory()

<Router history={newHistory}>
{isAuthenticated ? (
  <Layout>
    <Switch>
      <Route
         exact
         path="/clients"
         component={Clients}
        />
      <Route
         exact
         path="/staff"
         component={Staff}
        />
      <Redirect to="/clients" />
    </Switch>
  </Layout>
   ) : (
  <>
   <Route path="/login" component={Login} />
   <Redirect to="/login" />
  </>)}
</Router>
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda