Skip to content

Commit 8135304

Browse files
committed
Refactor routes
1 parent c205b1e commit 8135304

File tree

2 files changed

+49
-3
lines changed

2 files changed

+49
-3
lines changed

src/routes/PrivateRoute.tsx

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import React from 'react';
2+
import {
3+
Route,
4+
RouteProps,
5+
Redirect,
6+
RouteComponentProps,
7+
} from 'react-router-dom';
8+
import { connect } from 'react-redux';
9+
import { PATH } from 'src/constants/paths';
10+
11+
interface ReduxProps {
12+
isAuthenticated: boolean;
13+
}
14+
interface Props extends ReduxProps, RouteProps {
15+
component: React.ComponentType<RouteComponentProps>;
16+
}
17+
18+
const mapStateToProps = state => ({
19+
isAuthenticated: state.auth.isAuthenticated,
20+
});
21+
22+
const mapDispatchToProps = {};
23+
24+
const connector = connect(mapStateToProps, mapDispatchToProps);
25+
26+
const _PrivateRoute = (props: Props) => {
27+
const { isAuthenticated, component: Component, ...rest } = props;
28+
return (
29+
<Route
30+
{...rest}
31+
render={props => {
32+
if (!isAuthenticated && !localStorage.getItem('user')) {
33+
return <Redirect to={PATH.LOGIN} />;
34+
}
35+
return <Component {...props} />;
36+
}}
37+
/>
38+
);
39+
};
40+
41+
export const PrivateRoute = connector(_PrivateRoute);

src/routes/index.tsx

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { BrowserRouter } from 'react-router-dom';
33
import { PATH } from 'src/constants/paths';
44
import { Loading } from 'src/components/Loading';
55
import { Route, Switch } from 'react-router-dom';
6+
import { PrivateRoute } from './PrivateRoute';
67

78
// ---> Static pages
89
const HomePage = lazy(() => import('src/pages/HomePages/HomePage'));
@@ -46,11 +47,15 @@ export const Routes = () => {
4647
{/* Auth routes */}
4748
<Route exact path={PATH.LOGIN} component={LoginPage} />
4849
<Route exact path={PATH.REGISTER} component={RegisterPage} />
49-
<Route exact path={PATH.PROFILE} component={ProfilePage} />
50+
<PrivateRoute exact path={PATH.PROFILE} component={ProfilePage} />
5051

5152
{/* Products routes */}
52-
<Route exact path={PATH.PRODUCTS} component={ProductListPage} />
53-
<Route
53+
<PrivateRoute
54+
exact
55+
path={PATH.PRODUCTS}
56+
component={ProductListPage}
57+
/>
58+
<PrivateRoute
5459
exact
5560
path={PATH.PRODUCTS + '/:id'}
5661
component={ProductItemPage}

0 commit comments

Comments
 (0)