-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProfileInfo.tsx
More file actions
256 lines (241 loc) · 9.28 KB
/
ProfileInfo.tsx
File metadata and controls
256 lines (241 loc) · 9.28 KB
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
import { zodResolver } from '@hookform/resolvers/zod';
import { useEffect, useState } from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { myPageSchema } from '../../../shared/lib/formValidation';
import { formatPhoneNumber } from '../../../shared/utils/phoneFormatter';
import ProfileCircle from '../../../../design-system/ui/Profile';
import TertiaryButton from '../../../../design-system/ui/buttons/TertiaryButton';
import DefaultTextField from '../../../../design-system/ui/textFields/DefaultTextField';
import useAuthStore from '../../../app/provider/authStore';
import { useSendCertificationCode, useUserInfo, useUserUpdate, useVerifyCertificationCode } from '../../../features/join/hooks/useUserHook';
import { formatProfilName } from '../../../shared/lib/formatProfileName';
import Button from '../../../../design-system/ui/Button';
const ProfileInfo = () => {
const isLoggedIn = useAuthStore(state => state.isLoggedIn);
const { setName } = useAuthStore();
const { data, isLoading, error, refetch } = useUserInfo(isLoggedIn);
const { mutate: updateUser } = useUserUpdate();
const [isEditing, setIsEditing] = useState(false);
const { mutate: sendCode } = useSendCertificationCode();
const { mutate: verifyCode } = useVerifyCertificationCode();
const [isVerified, setIsVerified] = useState(false);
const {
register,
handleSubmit,
formState: { errors },
setValue,
watch
} = useForm<{ name: string; phone: string }>({
defaultValues: { name: data?.name || '', phone: data?.phoneNumber || '' },
resolver: zodResolver(myPageSchema),
});
const phoneValue = watch('phone');
useEffect(() => {
if (data) {
setValue('name', data.name);
setValue('phone', data.phoneNumber);
}
}, [data, setValue]);
const handlePhoneChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const formatted = formatPhoneNumber(e.target.value);
setValue('phone', formatted, { shouldValidate: true });
};
const onSubmit: SubmitHandler<{ name: string; phone: string }> = formData => {
const { name, phone } = formData;
if (!data?.id) {
alert('사용자 정보를 불러오는 데 실패했습니다. 다시 시도해주세요.');
return;
}
const updatedData = {
id: data.id,
name: name,
email: data.email,
phoneNumber: phone,
};
updateUser(updatedData, {
onSuccess: () => {
setName(name);
refetch();
setIsEditing(false);
setIsVerified(false);
alert('정보가 성공적으로 업데이트 되었습니다.')
},
onError: () => {
alert('정보 업데이트에 실패했습니다. 다시 시도해주세요.');
},
});
};
// 전화번호 인증
const [isVerifyVisible, setIsVerifyVisible] = useState(true);
const [verificationCode, setVerificationCode] = useState('');
const [timer, setTimer] = useState(0);
//인증번호 발급
const handlePhoneVerifyClick = () => {
if (!phoneValue) {
alert('연락처를 입력해주세요.');
return;
}
// //인증api호출
sendCode({ phoneNumber: phoneValue }, {
onSuccess: () => {
setIsVerifyVisible(true);
setTimer(180);
}
});
};
// 인증번호 확인
const handleVerifySubmit = () => {
if (!verificationCode || verificationCode.length !== 6) {
alert('6자리 인증번호를 입력해주세요.');
return;
}
verifyCode({ phoneNumber: phoneValue, certificationCode: verificationCode }, {
onSuccess: () => {
setIsVerifyVisible(false);
setIsVerified(true);
}
});
};
useEffect(() => {
if (isVerifyVisible && timer > 0) {
const interval = setInterval(() => setTimer((prev) => prev - 1), 1000);
return () => clearInterval(interval);
}
}, [timer, isVerifyVisible]);
const formatTime = (seconds: number) => {
const m = String(Math.floor(seconds / 60)).padStart(2, '0');
const s = String(seconds % 60).padStart(2, '0');
return `${m}:${s}`;
};
if (isLoading) {
return <div>로딩 중...</div>;
}
if (error) {
return <div>정보를 불러오는데 실패했습니다. 다시 시도해주세요.</div>;
}
return (
<div className="relative w-full h-52 md:h-56">
<div className="absolute inset-0 bg-main rounded-[10px]" />
<div className="relative z-10 bg-dashboardBg rounded-[10px] p-5 ml-2 h-full">
<div className="flex flex-col items-start h-full">
<h1 className="text-20 md:text-22 font-bold">프로필 정보</h1>
{!isEditing ? (
<>
<div className="flex items-center gap-3">
<ProfileCircle
profile="userProfile"
name={formatProfilName(data?.name || '')}
className="w-16 h-16 md:w-18 md:h-18 text-xl md:text-2xl"
/>
<div className="flex flex-col gap-1 py-5 md:py-7 mb-2">
<span className="text-17 md:text-19 font-bold">{data?.name}</span>
<span className="text-14 md:text-16 text-gray-500">{data?.phoneNumber}</span>
</div>
</div>
<TertiaryButton
label="수정하기"
type="button"
color="pink"
size="full"
onClick={() => setIsEditing(true)}
/>
</>
) : (
<form onSubmit={handleSubmit(onSubmit)} className="w-full">
<div className="flex py-2 md:py-3 gap-3">
<ProfileCircle
profile="userProfile"
name={formatProfilName(data?.name || '')}
className="w-16 h-16 md:w-18 md:h-18 text-xl md:text-2xl"
/>
<div className="flex flex-col gap-1 flex-1">
<DefaultTextField
{...register('name')}
errorPosition="bottom"
errorMessage={errors.name?.message}
className="h-9"
/>
<div className="flex gap-2 items-center">
<DefaultTextField
{...register('phone')}
onChange={handlePhoneChange}
className="h-9 flex-1"
/>
<Button
type="button"
label="인증하기"
onClick={handlePhoneVerifyClick}
className="h-9 sm:h-8 rounded-md w-24"
/>
</div>
{isVerifyVisible && (
<div className="mt-3 p-4 bg-white rounded-md shadow-md border border-gray-300">
<div className="flex gap-2 mb-2">
<DefaultTextField
placeholder="인증번호 6자리"
value={verificationCode}
onChange={(e) => setVerificationCode(e.target.value)}
className="h-9 flex-1"
/>
<Button
type="button"
label="확인"
onClick={handleVerifySubmit}
className="h-9 px-3 rounded-md"
/>
</div>
<span className="text-xs text-gray-500 pl-1 mb-3 block">
남은 시간: {formatTime(timer)}
</span>
<TertiaryButton
label="취소하기"
type="button"
color="pink"
size="full"
onClick={() => {
setIsEditing(false);
setValue('name', data?.name || '');
setValue('phone', data?.phoneNumber || '');
setIsVerified(false);
setIsVerifyVisible(false);
setVerificationCode('');
}}
/>
</div>
)}
{!isVerifyVisible && (
<div className="flex gap-2 mt-2">
<TertiaryButton
label="취소하기"
type="button"
color="pink"
size="full"
onClick={() => {
setIsEditing(false);
setValue('name', data?.name || '');
setValue('phone', data?.phoneNumber || '');
setIsVerified(false);
setVerificationCode('');
}}
/>
<TertiaryButton
label="수정하기"
type="submit"
color="pink"
size="full"
disabled={
phoneValue !== data?.phoneNumber && !isVerified
}
/>
</div>
)}
</div>
</div>
</form>
)}
</div>
</div>
</div>
);
};
export default ProfileInfo;