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

93
Visualizações
Reactjs useEffect does not change state value when fetching data

I'm trying to implement a Protected Route, which firstly tries to get an authentification(api call) so it can display the Route. But somehow the state value doesnt change.. Do you got any idea?

const ProtectedRoute = ({ component: Component, ...rest }) => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const fetch = async () => {
    const result = await axios.get("http://localhost:5000/auth/", {
      withCredentials: true,
    });

    if (result.status >= 200 && result.status < 300) {
      setIsAuthenticated(true);
    } else {
      setIsAuthenticated(false);
    }
  };

  useEffect(() => {
    fetch();
  }, []);

  return (
    <Route
      {...rest}
      render={(props) => {
        if (isAuthenticated) {
          return <Component {...props} />;
        } else {
          return <Redirect to={"./loginUser"} />;
        }
      }}
    />
  );
};

export default ProtectedRoute;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

What you can do is to return something when the api call is still loading. Something like this :

const ProtectedRoute = ({ component: Component, ...rest }) => {
  const [isAuthenticated, setIsAuthenticated] = useState(undefined);
  const [isLoading, setIsLoading] = useState(false);

  const fetch = async () => {
    const result = await axios.get("http://localhost:5000/auth/", {
      withCredentials: true,
    });

    if (result.status >= 200 && result.status < 300) {
      setIsAuthenticated(true);
    } else {
      setIsAuthenticated(false);
    }
  };

  useEffect(() => {
    setIsLoading(true);
    fetch();
    setIsLoading(false);
  }, []);

  return (
    <Route
      {...rest}
      render={(props) => {
        if(isLoading) { // do something }
        else if (isAuthenticated !== undefined && !isLoading) {
          return <Component {...props} />;
        } else {
          return <Redirect to={"./loginUser"} />;
        }
      }}
    />
  );
};

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