File tree Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ import React , { useCallback , useEffect , useState } from 'react' ;
2
+ import { useDispatch } from 'react-redux' ;
3
+ import { setAuthenticated , setCurrentUser } from '@/store/slices/authSlice' ;
4
+ import { getCurrentUser } from '@/apis/auth' ;
5
+
6
+ import { getToken } from '@/helpers/local-storage' ;
7
+ import { goURL } from '@/helpers/router' ;
8
+
9
+ interface IProps {
10
+ children : React . ReactElement ;
11
+ }
12
+
13
+ const Auth : React . FC < IProps > = ( { children } ) => {
14
+ const [ renderRoute , setRenderRoute ] = useState ( false ) ;
15
+ const dispatch = useDispatch ( ) ;
16
+
17
+ const fetchCurrentUser = useCallback ( async ( ) => {
18
+ try {
19
+ const response = await getCurrentUser ( ) ;
20
+ if ( response && response . data ) {
21
+ dispatch ( setAuthenticated ( true ) ) ;
22
+ dispatch ( setCurrentUser ( response . data ) ) ;
23
+ }
24
+ } catch ( error ) {
25
+ goURL ( '/login' ) ;
26
+ }
27
+ setRenderRoute ( true ) ;
28
+ } , [ dispatch ] ) ;
29
+
30
+ useEffect ( ( ) => {
31
+ if ( ! getToken ( ) ) {
32
+ goURL ( '/login' ) ;
33
+ setRenderRoute ( true ) ;
34
+ } else {
35
+ fetchCurrentUser ( ) ;
36
+ }
37
+ // eslint-disable-next-line react-hooks/exhaustive-deps
38
+ } , [ ] ) ;
39
+
40
+ return renderRoute ? children : null ;
41
+ } ;
42
+
43
+ export default Auth ;
Original file line number Diff line number Diff line change @@ -44,6 +44,14 @@ const Main: React.FC = () => {
44
44
path = { path }
45
45
render = { props => {
46
46
updateDisplayLayout ( currentLayout , layout ) ;
47
+ /**
48
+ * Use this for authentication like admin page
49
+ */
50
+ // return (
51
+ // <Auth>
52
+ // <Component {...props} />
53
+ // </Auth>
54
+ // );
47
55
return < Component { ...props } /> ;
48
56
} }
49
57
{ ...rest }
You can’t perform that action at this time.
0 commit comments