0

I'm trying to implement into my lazy loading private routing so I can guard my app but when I try to navigate to a route using my private routing it's redirecting me to a blank page without any errors. What did I do wrong? here is my code:

App.js:

function App() {
  return (
    <>
      <div>
        <BrowserRouter>
          <main>
            <Routes>
              <Route
                path="/"
                element={
                  <Suspense fallback={<>...</>}>
                    <HomePage />
                  </Suspense>
                }
              />
              <Route path="/purchaseOrders" element={<PrivateRoute />}>
                <Route
                  path="/purchaseOrders"
                  element={
                    <Suspense fallback={<>...</>}>
                      <PurchaseOrders />
                    </Suspense>
                  }
                />
              </Route>
              <Route path="*" element={<HomePage />} />
            </Routes>
          </main>
        </BrowserRouter>
      </div>
    </>
  );
}

privateroute.js:

const PrivateRoute = () => {
  const auth = localStorage.getItem("token") == null ? false : true;
  return auth ? <Outlet /> : <Link to={Config.loginUrl} />;
};

export default PrivateRoute;
Ofir Sasson
  • 673
  • 4
  • 16
  • 39

1 Answers1

0

I solved it like that:

function App() {
  const { isLogin } = false; // add useAuth here

  const PrivateRouteWrapper = ({ element }) => {
    if (isLogin) {
      return element;
    } else {
      window.location.href = Config.loginUrl;
      return null;
    }
  };

  return (
    <div>
      <BrowserRouter>
        <main>
          <Routes>
            <Route
              path="/"
              element={
                <Suspense fallback={<>...</>}>
                  <PrivateRouteWrapper element={<HomePage />} />
                </Suspense>
              }
            />
            <Route
              path="/purchaseOrders"
              element={
                <Suspense fallback={<>...</>}>
                  <PrivateRouteWrapper element={<PurchaseOrders />} />
                </Suspense>
              }
            />
            <Route
              path="/auth"
              element={
                <Suspense fallback={<>...</>}>
                  <Authentication />
                  <PrivateRouteWrapper element={<Authentication />} />
                </Suspense>
              }
            />

            <Route
              path="/table"
              element={
                <Suspense fallback={<>...</>}>
                  <PrivateRouteWrapper element={<TablePage />} />
                </Suspense>
              }
            />
            <Route
              path="*"
              element={<PrivateRouteWrapper element={<HomePage />} />}
            />
          </Routes>
        </main>
      </BrowserRouter>
    </div>
  );
}
Ofir Sasson
  • 673
  • 4
  • 16
  • 39