@@ -5,42 +5,42 @@ import "./index.css";
55import { useCookies } from "react-cookie" ;
66
77function Index ( ) {
8- const [ user , setUser ] = useState < UserDataT > ( ) ;
9- const [ , navigate ] = useLocation ( ) ;
10- const [ cookies , , removeCookie ] = useCookies ( [ "session" ] ) ;
11-
12- async function fetchUser ( ) {
13- let resp : Response ;
14-
15- if ( ! cookies . session ) {
16- return navigate ( "/login" ) ;
17- }
18-
19- try {
20- resp = await fetch ( "/users/@me" , { credentials : "include" } ) ;
21- } catch ( error ) {
22- console . error ( error ) ;
23- return navigate ( "/login" ) ;
24- }
25-
26- if ( ! resp . ok ) {
27- throw new Error ( `Unable to fetch user data from API: ${ resp . status } ` ) ;
28- }
29-
30- const data : UserDataT = await resp . json ( ) ;
31- if ( ! data ) {
32- removeCookie ( "session" , cookies . session ) ;
33- return navigate ( "/login" ) ;
34- }
35-
36- setUser ( data ) ;
37- }
38-
39- useEffect ( ( ) => {
40- fetchUser ( ) ;
41- } , [ ] ) ;
42-
43- return < > { user ?. name } </ > ;
8+ const [ user , setUser ] = useState < UserDataT > ( ) ;
9+ const [ , navigate ] = useLocation ( ) ;
10+ const [ cookies , , removeCookie ] = useCookies ( [ "session" ] ) ;
11+
12+ async function fetchUser ( ) {
13+ let resp : Response ;
14+
15+ if ( ! cookies . session ) {
16+ return navigate ( "/login" ) ;
17+ }
18+
19+ try {
20+ resp = await fetch ( "/users/@me" , { credentials : "include" } ) ;
21+ } catch ( error ) {
22+ console . error ( error ) ;
23+ return navigate ( "/login" ) ;
24+ }
25+
26+ if ( ! resp . ok ) {
27+ throw new Error ( `Unable to fetch user data from API: ${ resp . status } ` ) ;
28+ }
29+
30+ const data : UserDataT = await resp . json ( ) ;
31+ if ( ! data ) {
32+ removeCookie ( "session" , cookies . session ) ;
33+ return navigate ( "/login" ) ;
34+ }
35+
36+ setUser ( data ) ;
37+ }
38+
39+ useEffect ( ( ) => {
40+ fetchUser ( ) ;
41+ } , [ ] ) ;
42+
43+ return < > { user ?. name } </ > ;
4444}
4545
4646export default Index ;
0 commit comments