1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
|
"use client"
import * as React from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { toast } from "@/hooks/use-toast"
import { Button } from "@/components/ui/button"
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { findUserById } from "@/lib/admin-users/service"
import { useSession } from "next-auth/react";
import { updateUserProfileImage } from "@/lib/users/service"
const accountFormSchema = z.object({
name: z
.string()
.min(2, {
message: "Name must be at least 2 characters.",
})
.max(30, {
message: "Name must not be longer than 30 characters.",
}),
email: z.string().email(),
company: z
.string()
.min(2, {
message: "Name must be at least 2 characters.",
})
.max(30, {
message: "Name must not be longer than 30 characters.",
}),
imageFile: z.any().optional(),
})
type AccountFormValues = z.infer<typeof accountFormSchema>
export function AccountForm() {
const { data: session } = useSession();
const userId = session?.user.id || ""
const [previewUrl, setPreviewUrl] = React.useState<string | null>(null)
const form = useForm<AccountFormValues>({
resolver: zodResolver(accountFormSchema),
defaultValues: {
name: "",
company: "",
email: "",
imageFile: null,
},
})
// Fetch data in useEffect
React.useEffect(() => {
console.log("Form state changed: ", form.getValues());
async function fetchUser() {
try {
const data = await findUserById(Number(userId))
if (data) {
// Also reset the form's default values
form.reset({
name: data.user_name || "",
company: data.company_name || "",
email: data.user_email || "",
imageFile: data.user_image, // no file to begin with
})
}
} catch (error) {
console.error("Failed to fetch user data:", error)
}
}
if (userId) {
fetchUser()
}
}, [userId, form])
async function onSubmit(data: AccountFormValues) {
// RHF가 추적한 dirtyFields를 가져옵니다.
const { dirtyFields } = form.formState
// 변경된 필드가 전혀 없다면 => 업데이트 스킵
if (Object.keys(dirtyFields).length === 0) {
toast({
title: "No changes",
description: "Nothing to update",
})
return
}
// 바뀐 파일만 업로드
let imageFile: File | null = null
if (dirtyFields.imageFile && data.imageFile && data.imageFile.length > 0) {
// 새로 업로드한 파일
imageFile = data.imageFile[0]
}
// FormData 생성
const formData = new FormData()
formData.append("userId", userId)
formData.append("name", data.name)
formData.append("company", data.company)
formData.append("email", data.email)
if (imageFile) {
formData.append("file", imageFile)
}
try {
// 서버 액션(또는 API) 호출
await updateUserProfileImage(formData)
toast({
title: "Account updated",
description: "User updated successfully!",
})
} catch (error: any) {
toast({
title: "Error",
description: `Error: ${error.message ?? error}`,
variant: "destructive",
})
}
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Name</FormLabel>
<FormControl>
<Input placeholder="Your name" {...field} />
</FormControl>
<FormDescription>
This is the name that will be displayed on your profile and in
emails.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input placeholder="Your Email" {...field} />
</FormControl>
<FormDescription>
This is the email that will be used on login. If you want change it, please be careful.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="company"
render={({ field }) => (
<FormItem>
<FormLabel>Company</FormLabel>
<FormControl>
<Input
placeholder="Your Company name"
{...field}
readOnly
className="cursor-not-allowed bg-slate-50"
/>
</FormControl>
<FormDescription>
This is the name that will be displayed on your profile and in
emails.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
{/* 이미지 업로드 */}
<FormField
control={form.control}
name="imageFile"
render={({ field }) => (
<FormItem>
<FormLabel>Profile Image</FormLabel>
<FormControl>
<div className="space-y-2">
<Input
type="file"
accept="image/*"
onChange={(e) => {
field.onChange(e.target.files)
if (e.target.files && e.target.files.length > 0) {
// 로컬 미리보기 URL
const file = e.target.files[0]
const url = URL.createObjectURL(file)
setPreviewUrl(url)
}
}}
/>
{previewUrl ? (
<img src={previewUrl} alt="Local Preview" width={200}/>
) : (
typeof field.value === "string" &&
field.value && (
<img
src={`/profiles/${field.value}`}
alt="Server Image"
width={200}
/>
)
)}
</div>
</FormControl>
<FormDescription>
Upload your profile image.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit">Update account</Button>
</form>
</Form>
)
}
|