Skip to content

Commit

Permalink
fix: #199 - 유저정보 form 버그 수정
Browse files Browse the repository at this point in the history
유저정보 form 버그 수정
  • Loading branch information
bomi8489 authored Dec 2, 2023
2 parents 38253c1 + 94c6ae7 commit 5a96cc6
Show file tree
Hide file tree
Showing 7 changed files with 81 additions and 39 deletions.
7 changes: 2 additions & 5 deletions src/components/Login/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,10 @@ const Login = () => {
</div>
<Button
type="button"
onClick={() => router.push('/kakaoLogin')}
className="button button-md flex w-full items-center justify-center border-none bg-yellow-400 px-3 py-2.5">
<ChatBubbleOvalLeftIcon className="h-6 w-6 text-gray-800" />
<div
onClick={() => router.push('/kakaoLogin')}
className="text-sm font-bold text-gray-800">
카카오로 시작하기
</div>
<div className="text-sm font-bold text-gray-800">카카오로 시작하기</div>
</Button>
</div>
)
Expand Down
88 changes: 61 additions & 27 deletions src/components/UserInfoForm/UserInfoForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { fetchPostUserProfile } from '@/services/user/profile/profile'
import { UserProfileResBody } from '@/types'
import { cls } from '@/utils'
import { CheckIcon } from '@heroicons/react/24/solid'
import Cookies from 'js-cookie'
import { useRouter } from 'next/navigation'
import Button from '../common/Button/Button'
import { CATEGORIES } from '../common/CategoryList/constants'
Expand Down Expand Up @@ -42,6 +43,10 @@ const UserInfoForm = ({ userData, formType }: UserInfoFormProps) => {
setThumnail(userData?.profileImagePath)
}, [userData?.profileImagePath])

useEffect(() => {
formType === 'Setting' && setVerification(true)
}, [formType])

const emailRegex =
/^[a-zA-Z0-9.!#$%&'*+/=?&_`{|}~-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-]/
const nickNameRegex = /^[a-zA-Zㄱ-힣0-9]*$/
Expand All @@ -57,7 +62,7 @@ const UserInfoForm = ({ userData, formType }: UserInfoFormProps) => {
nickname: userData?.nickname || '',
aboutMe: userData?.aboutMe || '',
newsEmail: userData?.newsEmail || '',
favoriteCategory: userData?.favoriteCategory || 'ENTER_ART',
favoriteCategory: userData?.favoriteCategory || '',
isSubscribed: userData?.isSubscribed || false,
},
})
Expand All @@ -76,22 +81,38 @@ const UserInfoForm = ({ userData, formType }: UserInfoFormProps) => {
}
}

const handleEmailInput = () => {
setVerification(false)
setIsEmailAuthOpen(false)
}

const handleEmailAuth = async (email: string) => {
try {
await fetchPostEmail({ email })
const response = await fetchPostEmail({ email })

if (response.errorCode) {
response.errorCode === 'M001' && setVerification(true)
return
}

notify('success', '인증번호를 발송했습니다.')
setIsEmailAuthOpen(true)
} catch (e) {
setVerification(true)
notify('error', '인증번호 발송에 실패했습니다.')
}
}

const handleCheckAuthNum = async (code: string) => {
const verification = await fetchPostEmailVerify({
email: getValues('newsEmail'),
code,
})
setVerification(verification.isVerificate)
notify('success', '인증되었습니다.')
try {
const verification = await fetchPostEmailVerify({
email: getValues('newsEmail'),
code,
})
setVerification(verification.isVerificate)
notify('success', '인증되었습니다.')
} catch (e) {
notify('error', '인증에 실패했습니다.')
}
}

const handleClickCheckButton = () => {
Expand All @@ -102,23 +123,34 @@ const UserInfoForm = ({ userData, formType }: UserInfoFormProps) => {
const handleRegisterLinkHub = async (
data: RegisterReqBody & EmailVerifyReqBody,
) => {
await registerLinkHub(data, imageFile)
notify('success', '회원가입 되었습니다.')
router.replace('/login')
try {
const { jwt } = await registerLinkHub(data, imageFile)
if (jwt) {
notify('success', '회원가입 되었습니다.')
Cookies.set('Auth-token', jwt || '')
router.replace('/')
}
} catch (e) {
notify('error', '회원가입에 실패하였습니다.')
}
}

const handleSettingUser = async (
data: RegisterReqBody & EmailVerifyReqBody,
) => {
userData?.memberId &&
(await fetchPostUserProfile(userData?.memberId, data, imageFile))
notify('success', '수정되었습니다.')
router.back()
try {
userData?.memberId &&
(await fetchPostUserProfile(userData?.memberId, data, imageFile))
notify('success', '수정되었습니다.')
router.back()
} catch (e) {
notify('error', '수정에 실패했습니다.')
}
}

const handleWithdrawButton = () => {
// Todo: 회원탈퇴 로직
notify('info', '미구현된 기능입니다.')
notify('info', '서비스 준비 중입니다.')
}

return (
Expand All @@ -135,6 +167,7 @@ const UserInfoForm = ({ userData, formType }: UserInfoFormProps) => {
ref={selectUserImage}
onChange={handleFileChange}
hidden
accept=".jpg, .png, .svg"
/>
<div onClick={() => selectUserImage?.current?.click()}>
<Avatar
Expand All @@ -150,19 +183,19 @@ const UserInfoForm = ({ userData, formType }: UserInfoFormProps) => {
<div>
<Input
{...register('nickname', {
required: '닉네임을 입력해 주세요',
required: '닉네임을 입력해 주세요.',
minLength: {
value: 2,
message: '닉네임은 최소 2글자 이상이어야 합니다.',
message: '닉네임은 2자 이상 10자 이하로 작성해야 합니다.',
},
maxLength: {
value: 10,
message: '닉네임은 10글자 이하여야 합니다.',
message: '닉네임은 2자 이상 10자 이하로 작성해야 합니다.',
},
pattern: nickNameRegex,
})}
label="닉네임"
placeholder="nickname"
placeholder="닉네임을 입력해 주세요."
validation={
errors.nickname?.type === 'pattern'
? '닉네임에는 공백이나 특수문자를 사용할 수 없습니다.'
Expand All @@ -175,11 +208,11 @@ const UserInfoForm = ({ userData, formType }: UserInfoFormProps) => {
{...register('aboutMe', {
maxLength: {
value: 50,
message: '한줄 소개는 50글자 이하여야 합니다.',
message: '한줄 소개는 50자 이하로 작성해야 합니다.',
},
})}
label="한줄 소개"
placeholder="aboutMe"
placeholder="한줄 소개를 입력해 주세요."
validation={errors.aboutMe?.message}
/>
</div>
Expand All @@ -189,21 +222,22 @@ const UserInfoForm = ({ userData, formType }: UserInfoFormProps) => {
required: '이메일을 입력해 주세요',
maxLength: {
value: 300,
message: '이메일의 길이가 너무 깁니다.',
message: '이메일은 300자 이하로 작성해야 합니다.',
},
pattern: emailRegex,
})}
validation={
errors.newsEmail?.type === 'pattern'
? '이메일 양식에 맞게 입력해 주세요'
? '이메일 형식이 아닙니다.'
: errors.newsEmail?.message
}
label="이메일"
placeholder="Email"
inputButton
placeholder="이메일을 입력해 주세요."
inputButton={!isVerification}
buttonText="인증번호 전송"
buttonColor="gray"
onButtonClick={() => handleEmailAuth(getValues('newsEmail'))}
onChange={handleEmailInput}
/>
</div>
{isEmailAuthOpen && (
Expand Down
4 changes: 3 additions & 1 deletion src/components/UserInfoForm/hooks/useRegister.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@ const useRegister = () => {
const registerLinkHub = async (data: RegisterReqBody, imageFile?: File) => {
data.socialId = Cookies.get('Social-Id') || ''
data.provider = Cookies.get('Provider') || ''
await registerUser(data, imageFile)
const { jwt } = await registerUser(data, imageFile)
Cookies.remove('Social-Id')
Cookies.remove('Provider')

return { jwt }
}

return { registerLinkHub }
Expand Down
3 changes: 3 additions & 0 deletions src/components/common/Input/Input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export interface InputProps {
validation?: string
disabled?: boolean
onButtonClick?: (e?: React.MouseEvent<HTMLButtonElement>) => void
onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void
}

const Input = forwardRef(
Expand All @@ -27,6 +28,7 @@ const Input = forwardRef(
validation,
disabled,
onButtonClick,
onChange,
...rest
}: InputProps,
ref?: ForwardedRef<HTMLInputElement>,
Expand All @@ -52,6 +54,7 @@ const Input = forwardRef(
)}
placeholder={placeholder}
disabled={disabled}
onChange={onChange}
{...rest}
/>
{inputButton && (
Expand Down
6 changes: 3 additions & 3 deletions src/components/common/Sidebar/hooks/useSidebar.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Dispatch, SetStateAction, useState } from 'react'
import { kakaoLogout } from '@/services/auth'
import Cookies from 'js-cookie'
import { notify } from '../../Toast/Toast'

type SpaceType = '내 스페이스' | '즐겨찾기'

Expand All @@ -17,11 +18,10 @@ const useSidebar = ({ sidebarRef, setIsOpen, onClose }: useSidebarProps) => {
try {
await kakaoLogout()
Cookies.remove('Auth-token')
location.reload()
alert('로그아웃 되었습니다.')
notify('info', '로그아웃 되었습니다.')
onClose()
} catch (e) {
alert('다시 시도해 주세요.')
notify('error', '로그아웃에 실패하였습니다.')
}
}

Expand Down
4 changes: 3 additions & 1 deletion src/lib/fetchAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,10 @@ class FetchAPI {
)
break
}
return data
} else {
return type === 'delete' ? response : response.json()
}
return type === 'delete' ? response : response.json()
}

public static getInstance(): FetchAPI {
Expand Down
8 changes: 6 additions & 2 deletions src/services/email/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,12 @@ const fetchPostEmailVerify = async (
data: EmailVerifyReqBody & EmailReqBody,
) => {
const path = '/api/email-verify'
const response = await apiClient.post(path, data)
return response
try {
const response = await apiClient.post(path, data)
return response
} catch (e) {
if (e instanceof Error) throw new Error(e.message)
}
}

export { fetchPostEmail, fetchPostEmailVerify }

0 comments on commit 5a96cc6

Please sign in to comment.