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 ( -
-