1
+ "use client" ;
2
+
3
+ import { Button } from "@/components/ui/button"
4
+ import { getSession } from "next-auth/react" ;
5
+ import { useRouter } from "next/navigation" ;
6
+ import { useState } from "react" ;
7
+
8
+ async function handleSubmit ( {
9
+ typedName,
10
+ } : {
11
+ typedName : string ;
12
+ } ) {
13
+ const session = await getSession ( ) ;
14
+ const uid = session ?. user . id ;
15
+ const displayName = session ?. user . name ;
16
+
17
+ if ( displayName === typedName ) {
18
+ console . error ( "The current username and the new one is still the same!" ) ;
19
+ throw new Error ( "The current username and the new one is still the same!" )
20
+ }
21
+
22
+ const response = await fetch ( "/api/user-actions/edit-username" , {
23
+ headers : {
24
+ Authorization : `userId ${ uid } `
25
+ } ,
26
+ method : "POST" ,
27
+ body : JSON . stringify ( { newName : typedName } )
28
+ } ) ;
29
+
30
+ if ( response . status === 200 ) {
31
+ return "succes" ;
32
+ } else {
33
+ return "fail" ;
34
+ }
35
+ }
36
+
37
+ export default function ChangeNameForm ( ) {
38
+ const [ typedName , setTypedName ] = useState ( "" ) ;
39
+ const router = useRouter ( ) ;
40
+ return (
41
+ < >
42
+ < form onSubmit = { async ( e ) => {
43
+ e . preventDefault ( ) ;
44
+ const result = await handleSubmit ( { typedName } ) ;
45
+ if ( result === "fail" ) {
46
+ /** show some UI on every error here.
47
+ * This will be polished soon.
48
+ */
49
+ console . error ( "something went wrong!" ) ;
50
+ } else {
51
+ router . refresh ( ) ;
52
+ }
53
+ } } className = "z-10 w-[90%] p-6 h-48 max-w-[30rem] rounded-md shadow-monochrome shadow-lg bg-secondary flex flex-col justify-center gap-4" >
54
+ < div title = "Type in new username" >
55
+ < label htmlFor = "username-input" className = "text-lg lg:text-xl" > Type in your new username</ label >
56
+ < div className = "block cursor-text rounded-sm relative w-full h-12 p-3 mt-2 border-[1px] border-solid border-primary" >
57
+ < input
58
+ type = "text"
59
+ name = "username-input"
60
+ placeholder = { "your new username" }
61
+ id = "username-input"
62
+ onChange = { ( e ) => setTypedName ( e . target . value ) }
63
+ className = "outline-none bg-transparent h-full w-full z-10 relative"
64
+ required
65
+ value = { typedName }
66
+ minLength = { 3 }
67
+ />
68
+ </ div >
69
+ </ div >
70
+ < div >
71
+ < Button
72
+ type = "submit"
73
+ variant = { "destructive" }
74
+ className = "py-6 w-full text-lg"
75
+ >
76
+ Save
77
+ </ Button >
78
+ </ div >
79
+ </ form >
80
+ </ >
81
+ ) ;
82
+ } ;
0 commit comments