From 504a66132287c89e5cbcc4a659f1cd4275ca43a4 Mon Sep 17 00:00:00 2001 From: Ji Hyeong Lee <115636461+Jihyeong00@users.noreply.github.com> Date: Thu, 6 Jun 2024 00:24:57 +0900 Subject: [PATCH] =?UTF-8?q?refactor:=20=EA=B2=80=EC=83=89=EC=B0=BD?= =?UTF-8?q?=EC=9D=84=20RHF=20+=20ZOD=EB=A1=9C=20=EB=B3=80=EA=B2=BD?= =?UTF-8?q?=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../search/schema/search-keyword-schema.ts | 4 +- src/features/search/ui/HeaderSearchBar.tsx | 42 +++++++------------ .../search/ui/header-search-bar.module.scss | 1 - 3 files changed, 18 insertions(+), 29 deletions(-) diff --git a/src/features/search/schema/search-keyword-schema.ts b/src/features/search/schema/search-keyword-schema.ts index e33e11e..aab1c71 100644 --- a/src/features/search/schema/search-keyword-schema.ts +++ b/src/features/search/schema/search-keyword-schema.ts @@ -1,3 +1,5 @@ import { z } from 'zod' -export const searchKeywordSchema = z.string().min(2, '검색의 최소 길이 (2글자)를 넘지 않습니다.') +export const searchKeywordSchema = z.object({ + search: z.string(), +}) diff --git a/src/features/search/ui/HeaderSearchBar.tsx b/src/features/search/ui/HeaderSearchBar.tsx index 2d1b3ae..84f399d 100644 --- a/src/features/search/ui/HeaderSearchBar.tsx +++ b/src/features/search/ui/HeaderSearchBar.tsx @@ -1,10 +1,12 @@ 'use client' +import { zodResolver } from '@hookform/resolvers/zod' import classNames from 'classnames' import Image from 'next/image' import { useRouter } from 'next/navigation' import { useState } from 'react' -import { ZodError } from 'zod' +import { SubmitHandler, useForm } from 'react-hook-form' +import { z } from 'zod' import { searchKeywordSchema } from '@/features/search/schema' import { SITE_PATH } from '@/shared/constants' @@ -16,29 +18,16 @@ export function HeaderSearchBar() { const [isFocus, setIsFocus] = useState(false) const router = useRouter() - const onSubmit = (e: FormData) => { - const keyword = e.get('keyword') - - if (typeof keyword !== 'string') { - return - } - - try { - searchKeywordSchema.parse(keyword) - router.push(SITE_PATH.search(keyword)) - } catch (error) { - if (error instanceof ZodError) { - console.error('Validation failed. Errors:', error.errors) - } else if (error instanceof Error) { - console.error('Unexpected error during validation:', error.message) - } - } + const onSubmit: SubmitHandler> = async ({ search }) => { + router.push(SITE_PATH.search(search)) } - const resetValue = () => { - const input = document.getElementById('keyword') as HTMLInputElement - input.value = '' - } + const { handleSubmit, register, reset } = useForm>({ + resolver: zodResolver(searchKeywordSchema), + defaultValues: { + search: '', + }, + }) const onFocus = () => { setIsFocus(true) @@ -49,21 +38,20 @@ export function HeaderSearchBar() { } return ( -
-