File tree 1 file changed +48
-0
lines changed 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Submit to API helper function
2
+ export const submitToAPI = async (
3
+ apiKey : string ,
4
+ submitUrl : string ,
5
+ body : BodyInit | null | undefined ,
6
+ ) => {
7
+ let res : Response | null = null
8
+ let isSubmitted = false
9
+ let isError = false
10
+ let errorMessage = ''
11
+
12
+ // Headers
13
+ const headers = {
14
+ 'Content-Type' : 'application/json' ,
15
+ 'Accept' : 'application/json' ,
16
+ 'Authorization' : `Bearer ${ apiKey } ` ,
17
+ }
18
+
19
+ // Pass body to a POST request
20
+ try {
21
+ res = await fetch ( submitUrl , {
22
+ method : 'POST' ,
23
+ headers,
24
+ body,
25
+ } )
26
+
27
+ // Mark the submission successful, otherwise return error state
28
+ if ( res . ok ) {
29
+ isSubmitted = true
30
+ }
31
+ else {
32
+ throw new Error ( `${ res . status } Error` )
33
+ }
34
+ }
35
+ catch ( error ) {
36
+ isError = true
37
+ if ( error instanceof Error ) {
38
+ errorMessage = error . message
39
+ }
40
+ }
41
+
42
+ return {
43
+ res,
44
+ isSubmitted,
45
+ isError,
46
+ errorMessage,
47
+ }
48
+ }
You can’t perform that action at this time.
0 commit comments