1- import { Suspense , useState } from 'react' ;
2- import { Route , Routes } from 'react-router-dom' ;
1+ import { useState , useEffect } from 'react' ;
2+ import { Route , Routes , useLocation , useNavigate } from 'react-router-dom' ;
3+ import { getAuth } from 'src/apis/auth' ;
34import UserContext from 'src/contexts/user' ;
45import {
56 LoadingPage ,
@@ -14,18 +15,38 @@ import 'styles/reset.scss';
1415
1516function App ( ) {
1617 const [ user , setUser ] = useState < User | null > ( null ) ;
18+ const [ isLoaded , setIsLoaded ] = useState < boolean > ( false ) ;
1719
18- return (
19- < Suspense fallback = { < LoadingPage /> } >
20- < UserContext . Provider value = { { user, setUser } } >
21- < Routes >
22- < Route path = "/" element = { < LoginPage /> } />
23- < Route path = "/oauth" element = { < OAuthPage /> } />
24- < Route path = "/workspace/*" element = { < WorkspacePage /> } />
25- < Route path = "/404" element = { < NotFoundPage /> } />
26- </ Routes >
27- </ UserContext . Provider >
28- </ Suspense >
20+ const location = useLocation ( ) ;
21+ const navigate = useNavigate ( ) ;
22+
23+ const autoLogin = async ( ) => {
24+ const { user } = await getAuth ( ) ;
25+
26+ setIsLoaded ( true ) ;
27+
28+ setUser ( user ) ;
29+
30+ if ( user && ! / ^ \/ w o r k s p a c e ( \/ \d ) ? $ / . test ( location . pathname ) ) {
31+ navigate ( '/workspace' ) ;
32+ }
33+ } ;
34+
35+ useEffect ( ( ) => {
36+ autoLogin ( ) ;
37+ } , [ ] ) ;
38+
39+ return isLoaded ? (
40+ < UserContext . Provider value = { { user, setUser } } >
41+ < Routes >
42+ < Route path = "/" element = { < LoginPage /> } />
43+ < Route path = "/oauth" element = { < OAuthPage /> } />
44+ < Route path = "/workspace/*" element = { < WorkspacePage /> } />
45+ < Route path = "/404" element = { < NotFoundPage /> } />
46+ </ Routes >
47+ </ UserContext . Provider >
48+ ) : (
49+ < LoadingPage />
2950 ) ;
3051}
3152
0 commit comments