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


Solution 1:[1]

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;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Karim Chaari