1
+ "use client" ;
2
+
3
+ import { FormEvent , useState } from "react" ;
4
+ import axios from "axios" ;
5
+
1
6
import Button from "@/lib/components/Button/Button" ;
2
7
3
8
import BasicInformation from "./BasicInformation" ;
@@ -8,20 +13,82 @@ import ResumeInformation from "./ResumeInformation";
8
13
9
14
import styles from "./Form.module.scss" ;
10
15
16
+ const APPLY_PATH = "/api/user/apply" ;
17
+ const FIELDS_WITH_OTHER = [ "pronouns" , "ethnicity" , "school" , "major" ] ;
18
+
11
19
export default function Form ( ) {
20
+ const [ submitting , setSubmitting ] = useState ( false ) ;
21
+ const [ sessionExpired , setSessionExpired ] = useState ( false ) ;
22
+
23
+ const handleSubmit = async (
24
+ event : FormEvent < HTMLFormElement > ,
25
+ ) : Promise < void > => {
26
+ // Disable native post submission
27
+ event . preventDefault ( ) ;
28
+ setSubmitting ( true ) ;
29
+ setSessionExpired ( false ) ;
30
+
31
+ const formData = new FormData ( event . currentTarget ) ;
32
+
33
+ // Use other values when selected
34
+ for ( const field of FIELDS_WITH_OTHER ) {
35
+ const otherField = `other_${ field } ` ;
36
+ if ( formData . get ( field ) === "other" ) {
37
+ formData . set ( field , formData . get ( otherField ) ! ) ;
38
+ formData . delete ( otherField ) ;
39
+ }
40
+ }
41
+
42
+ const formEntries = Object . fromEntries ( formData . entries ( ) ) ;
43
+ console . debug ( formEntries ) ;
44
+
45
+ try {
46
+ const res = await axios . post ( APPLY_PATH , formData ) ;
47
+ if ( res . status === 201 ) {
48
+ console . log ( "Application submitted" ) ;
49
+ // TODO: show submitted message
50
+ }
51
+ } catch ( err ) {
52
+ console . error ( err ) ;
53
+ if ( axios . isAxiosError ( err ) ) {
54
+ if ( err . response ?. status === 401 ) {
55
+ setSessionExpired ( true ) ;
56
+ }
57
+ }
58
+ }
59
+
60
+ setSubmitting ( false ) ;
61
+ } ;
62
+
63
+ const sessionExpiredMessage = (
64
+ < p className = "text-red-500 w-11/12" >
65
+ Your session has expired. Please{ " " }
66
+ < a
67
+ href = "/login"
68
+ target = "_blank"
69
+ className = "text-blue-600 underline"
70
+ >
71
+ log in from a new tab
72
+ </ a > { " " }
73
+ to restore your session and then try submitting again.
74
+ </ p >
75
+ ) ;
76
+
12
77
return (
13
78
< form
14
79
method = "post"
15
80
className = { `${ styles . form } text-[#000000] w-8/12 flex flex-col items-center py-12 gap-10 z-1 max-[800px]:w-9/12 max-[400px]:w-11/12` }
16
81
action = "/api/user/apply"
17
82
encType = "multipart/form-data"
83
+ onSubmit = { handleSubmit }
18
84
>
19
85
< BasicInformation />
20
86
< SchoolInformation />
21
87
< ProfileInformation />
22
88
< ResumeInformation />
23
89
< AgeInformation />
24
- < Button text = "Submit Application" />
90
+ < Button text = "Submit Application" disabled = { submitting } />
91
+ { sessionExpired && sessionExpiredMessage }
25
92
</ form >
26
93
) ;
27
94
}
0 commit comments