Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

201
Visualizações
React: private route not navigating

I am using a private route to navigate to a route after the user has logged in. However, I am facing an issue. I don't know why but my router is not transitioning to the desired route. Here's my code:

Routes.js

...
...
<PrivateRoute
  authenticated={localStorage.getItem("isAuthenticated")}
  path="/dashboard"
  component={DashBoard}
  exact
></PrivateRoute>

PrivateRoute.js

const PrivateRoute = ({ component: Component, authenticated, ...rest }) => (  
<Route
  {...rest}
  render={props =>
    authenticated ? (
      <Component {...rest} {...props} />
    ) : (
      <Redirect
        to={{
          pathname: '/',
          state: { from: props.location }
        }}
      />
    )
  }
/>
);

export default PrivateRoute;

Login.js

localStorage.setItem("isAuthenticated", true);
this.props.history.push('/dashboard');

Any help would be appreciated. Thanks!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Can you just try it?

PrivateRoute.js

const PrivateRoute = ({ component: Component, authenticated, ...rest }) => {
  console.log("authenticated",authenticated)//is it true or false?
  if (authenticated=="true")
    return (
      <Route {...rest}>
        {" "}
        <Component {...rest} {...props} />
      </Route>
    );
  else
    return (
      <Redirect
        to={{
          pathname: "/",
          state: { from: props.location },
        }}
      />
    );
};

export default PrivateRoute;
about 4 years ago · Juan Pablo Isaza Relatório

0

So, I found the solution.

authenticated={localStorage.getItem("isAuthenticated")}

the above was invoking the method at application bootstrap due to which I was having the value of null being stored in my authenticated variable so, I changed it to arrow function and passed the argument without invoking it like below:

authenticated={() => localStorage.getItem("isAuthenticated")}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda