V
V
Viktor2020-02-10 10:39:15
React
Viktor, 2020-02-10 10:39:15

How can routes be optimized?

There is a code:

<Switch>         
            <Route path="/login">
              { service.auth.isAuth ? <Redirect to="/" /> : <LoginPage />}  
            </Route>

            <Route path="/registration">
              { service.auth.isAuth ? <Redirect to="/" /> : <RegistrationPage />}
            </Route>  

            <Route exact path={['/', '/info']}>
              { !service.auth.isAuth ? <Redirect to="/login" /> : <InfoPage /> }               
            </Route>
            
            <Route path="/notes" exact>
              { !service.auth.isAuth ? <Redirect to="/login" /> : <NotesPage /> }              
            </Route>

            <Route path="/notes/:id" exact>
              { !service.auth.isAuth ? <Redirect to="/login" /> : <NoteDetails /> }              
            </Route>

            <Route path="/notes/edit/:id">
              { !service.auth.isAuth ? <Redirect to="/login" /> : <NoteEdit /> }             
            </Route>

            <Route path="/goods">
              { !service.auth.isAuth ? <Redirect to="/login" /> : <GoodsPage /> }              
            </Route>

            <Route path="/basket">
              { !service.auth.isAuth ? <Redirect to="/login" /> : <BasketPage /> }              
            </Route>

            <Route path="*">
              { service.auth.isAuth 
                ? <Alert title="Error 404" text="Page not found!" type="danger" />
                : <LoginPage />}                
            </Route>              
          </Switch>

Tell me how you can optimize so that in each route you do not prescribe a condition for checking authorization!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
1
1programmer, 2020-02-10
@polyak-888

Maybe something like that?

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={(props) => (
    !service.auth.isAuth
      ? <Component {...props} />
      : <Redirect to='/' />
  )} />
)

<PrivateRoute path='/info' component={InfoPage} />

M
Mikhail Osher, 2020-02-10
@miraage

I would remove checks from routes and move them to some useEffect in one of the root components like App or AuthProvider.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question