0

I am trying to separate react lazy in 2 separate modules , due to the fact that I want to make my private route take multi components not only one.

my current app.tsx module looks like the following :

import React, { useState, useEffect, useContext, lazy, Suspense } from 'react';
import { BrowserRouter as Router, Route, Switch, HashRouter, Redirect } from 'react-router-dom';
// Privite Route Component
import { PrivateRoute } from './components/routes/PrivateRoute';
import { NotFound } from './components/routes/NotFound';
// Components **********************************/
import Home from './components/Home/Home';
import { AuthAction } from './components/routes/AuthAction';
// Context API
import AuthProvider from './context/auth/AuthState';
// Lazy
const AppMain = lazy(() => import('././components/App/CentralHub'));

function App() {
  return (
    <Router>
      <AuthProvider>
        <Switch>
          <Route exact path='/' component={Home} />
          <PrivateRoute exact path='/app' component={AppMain} />
       />
          <PrivateRoute exact path='/auth/action' component={AuthAction} />
          <Route path='*' component={NotFound} />
        </Switch>
      </AuthProvider>
    </Router>
  );
}

export default App;

Would calling react suspense inside of a private route that receives a that target component as propose considered a bad idea? my private rout receives this component, as props from the app.tsx now the suspense action runs from the privet route, yet my component is getting imported still from out side form (the app.tsx) should I rather split private routes and lazy import the props component inside of the private route rather than from out side ? or would my current model considered clean regardless of the fact that lazy is working in other component than suspense dose ?

import React, { useContext, useEffect, Suspense } from 'react';
import { Redirect, Route, useHistory, useLocation } from 'react-router-dom';
import { useAppSelector } from '../../app/hooks';

interface Props {
  component: React.FC<any>;
  exact?: boolean;
  path: string;
}

export const PrivateRoute: React.FC<Props> = ({ component: Component, ...rest }) => {
  const location = useLocation();
  const authenticating = useAppSelector((state) => state.auth.authenticating);
  const currentUser = useAppSelector((state) => state.auth.currentUser);
  
  return (
    <>
      {location.pathname.startsWith('/app') && !authenticating && (
        <Route
          {...rest}
          render={(props) =>
            !currentUser?.authenticated /*Route Condtion*/ ? (
              <Redirect to='/' />
            ) : (
              <Suspense fallback={<div></div> /*null*/}>
                <Component {...props} />
              </Suspense>
            )
          }
        />
      )}
    </>
  );
};
Richardson
  • 1,804
  • 10
  • 38

0 Answers0