1- import { ChangeEvent , FormEvent , useState } from "react" ;
1+ import { ChangeEvent , useEffect , useState } from "react" ;
22import { useRouter } from "next/router" ;
33import Image from "next/image" ;
4+ import useDebounce from "@/hooks/useDebounce" ;
45
56export const SearchInput = ( ) => {
67 const router = useRouter ( ) ;
78 const [ value , setValue ] = useState ( "" ) ;
89
10+ const debouncedValue = useDebounce ( value , 200 ) ;
11+
912 const handleChange = ( e : ChangeEvent < HTMLInputElement > ) => {
13+ e . preventDefault ( ) ;
1014 setValue ( e . target . value ) ;
1115 } ;
1216
13- const handleSubmit = ( e : FormEvent < HTMLFormElement > ) => {
14- e . preventDefault ( ) ;
15- router . push ( {
16- pathname : router . pathname ,
17- query : { ...router . query , search : value } ,
18- } ) ;
17+ useEffect ( ( ) => {
18+ if ( debouncedValue ) {
19+ router . push ( {
20+ pathname : router . pathname ,
21+ query : { ...router . query , search : debouncedValue } ,
22+ } ) ;
23+ }
24+ } , [ debouncedValue ] ) ;
25+
26+ const handleClick = ( ) => {
1927 setValue ( "" ) ;
28+ router . push ( "/link" ) ;
2029 } ;
2130
2231 return (
2332 < form
24- onSubmit = { handleSubmit }
33+ onSubmit = { ( e ) => e . preventDefault ( ) }
2534 className = "flex gap-[8px] w-full h-[54px] items-center px-[16px] py-[15px] bg-gray-100 rounded-[10px] md:h-[54px] sm:h-[43px] transition-all"
2635 >
2736 < Image
@@ -36,6 +45,15 @@ export const SearchInput = () => {
3645 placeholder = "링크를 검색해 보세요."
3746 className = "flex-grow bg-transparent placeholder:text-gray-500"
3847 />
48+ { value && (
49+ < button
50+ className = "rounded-full bg-white size-6 font-bold text-gray-500 flex items-center justify-center"
51+ type = "button"
52+ onClick = { handleClick }
53+ >
54+ ×
55+ </ button >
56+ ) }
3957 </ form >
4058 ) ;
4159} ;
0 commit comments