I am learning the way how to guard the routes in react. Essentially I've followed this article https://bikashxsharma.medium.com/how-to-create-private-or-protected-route-in-react-router-v6-dd6ea6f65aea, but decided to change it slightly in a way that I retrieve userInfo based on the cookie stored in browser and not a localStorage.
This results in an infinite loop over which I am still scratching my head. Any suggestions:
import React, { useEffect, useState } from 'react';
import { Navigate, Outlet } from 'react-router';
import { userApi } from '../../api';
import { ROUTES } from '../../constants';
const ProtectedRoutes = () => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  useEffect(() => {
    async function getUsetInfo() {
      const userInfo = await userApi.getUserInfo();
      if (userInfo) {
        setIsLoggedIn(true);
      }
    }
    getUsetInfo();
  }, []);
  return isLoggedIn ? <Outlet /> : <Navigate to={ROUTES.signUp} />;
};
export default ProtectedRoutes;
Router usage:
import { ROUTES } from '../constants';
const App = () => {
  return (
    <BrowserRouter>
      <Routes>
        <Route path={ROUTES.home} element={<ProtectedRoutes />}>
          <Route path={ROUTES.home} element={<Layout />}>
            <Route path={ROUTES.leaderboard} element={<LeaderBoard />} />
          </Route>
          <Route path={ROUTES.profile} element={<Profile />} />
        </Route>
        <Route path={ROUTES.home} element={<PublicRoutes />}>
          <Route path={ROUTES.signUp} element={<Registration />} />
          <Route path={ROUTES.signIn} element={<Login />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
};
 
    