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

105
Visualizações
Prevent Component Rendering when i use navigate in react router dom v6

hi i'm doing protected routes using react router v6 it is redirecting fine but let's say i'm in /login and i'm not authenticated and i want to go to /dashboard here /dashboard will be rendered for some few miliseconds (i can see it ) then i will be redirected to /login how can i prevent that rendering. here's my code :

import { useEffect, useState } from "react";
import { Route, useNavigate } from "react-router-dom";
import { Auth } from "aws-amplify";

const protectedRoute = (Comp, route = "/login") => (props) => {
  const navigate = useNavigate();
  const checkAuthState = async () => {
    try {
      await Auth.currentAuthenticatedUser();
      console.log("React Router user authenticated ");
    } catch (err) {
      console.log("React Router we have an error");
      navigate(route);
    }
  };
  useEffect(() => {
    checkAuthState();
  });
  return <Comp {...props} />;
};

export default protectedRoute;

this is how i ordered my routes in App.js

 <Router>
      <Routes>
        <Route path="/" element={<Navigate to="/login" replace={true} />} />
        <Route path="/login" element={<Login />} />
        <Route path="dashboard/*" element={<Dashboard />} />
        <Route path="/signup" element={<Signup />} />
        <Route path="RecoverPassword" element={<RecoverPassword />} />
        <Route path="resetPassword" element={<ResetPassword />} />
        <Route path="verifycode" element={<VerifyCode />} />
        <Route path="policy" element={<>this is policy</>} />
      </Routes>
    </Router>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can create a flag to tell if the checking is don or not, while that you can show some loader to the user instead of the component.

onst protectedRoute = (Comp, route = "/login") => (props) => {
  const navigate = useNavigate();
  const loading = useState(false);
  
  const checkAuthState = async () => {
    // start checking, show loader
    setLoading(true)
    try {
      await Auth.currentAuthenticatedUser();
      console.log("React Router user authenticated ");
    } catch (err) {
      console.log("React Router we have an error");
      navigate(route);
    }
    
    // end checking, hide loader
    setLoading(false)
  };
  useEffect(() => {
    checkAuthState();
  }, []);
  
  if(loading) {
    return "loading..."
  }
  return <Comp {...props} />;
};

about 4 years ago · Juan Pablo Isaza Relatório

0

i got it you know what was happening is that useEffect will be executed when my component mounts (i returned redirection component so it will be rendered ) what i did is putting my component into a state initialized to empty <></> then when my protected route mounts i change the state to what i want to render

import { useEffect, useState } from "react";
import { Route, useNavigate } from "react-router-dom";
import { Auth } from "aws-amplify";

const protectedRoute = (Comp, route = "/login") => (props) => {
  const navigate = useNavigate();
  const [corps, setCorps] = useState(<></>);

  const checkAuthState = async () => {
    try {
      await Auth.currentAuthenticatedUser();
      console.log("React Router user authenticated ");
    } catch (err) {
      console.log("React Router we have an error");
      return navigate(route);
    }
  };
  useEffect(() => {
    checkAuthState();
    setCorps(<Comp {...props} />);
  }, []);

  return corps;
};

export default protectedRoute;
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