0

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>
  );
};
Ren
  • 944
  • 1
  • 13
  • 26

1 Answers1

1

Try to use a react-router-dom package instead of react-router

react-router vs react-router-dom, when to use one or the other?

Or you can add a isLoading state, when it's true show some <Loader /> component or return null

useEffect(() => {
    setIsLoading(true);

    async function getUsetInfo() {
      const userInfo = await userApi.getUserInfo();

      setIsLoading(false);

      if (userInfo) {
        setIsLoggedIn(true);
      }
    }
    getUsetInfo();
  }, []);
Arthur Arakelyan
  • 164
  • 1
  • 11