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

91
Vistas
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 Respuestas
Responde la pregunta

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 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