File tree Expand file tree Collapse file tree 1 file changed +22
-0
lines changed Expand file tree Collapse file tree 1 file changed +22
-0
lines changed Original file line number Diff line number Diff line change 1
1
'use client' ;
2
2
3
3
import { MagnifyingGlassIcon } from '@heroicons/react/24/outline' ;
4
+ import { useSearchParams , usePathname , useRouter } from 'next/navigation' ;
5
+ import { useDebouncedCallback } from 'use-debounce' ;
4
6
5
7
export default function Search ( { placeholder } : { placeholder : string } ) {
8
+ const searchParams = useSearchParams ( ) ;
9
+ const pathname = usePathname ( ) ;
10
+ const { replace } = useRouter ( ) ;
11
+
12
+ const handleSearch = useDebouncedCallback ( ( term : string ) => {
13
+ const params = new URLSearchParams ( searchParams ) ;
14
+ params . set ( 'page' , '1' ) ;
15
+
16
+ if ( term ) {
17
+ params . set ( 'query' , term ) ;
18
+ } else {
19
+ params . delete ( 'query' ) ;
20
+ }
21
+ replace ( `${ pathname } ?${ params . toString ( ) } ` )
22
+ } , 300 ) ;
23
+
6
24
return (
7
25
< div className = "relative flex flex-1 flex-shrink-0" >
8
26
< label htmlFor = "search" className = "sr-only" >
@@ -11,6 +29,10 @@ export default function Search({ placeholder }: { placeholder: string }) {
11
29
< input
12
30
className = "peer block w-full rounded-md border border-gray-200 py-[9px] pl-10 text-sm outline-2 placeholder:text-gray-500"
13
31
placeholder = { placeholder }
32
+ onChange = { ( e ) => {
33
+ handleSearch ( e . target . value )
34
+ } }
35
+ defaultValue = { searchParams . get ( 'query' ) ?. toString ( ) }
14
36
/>
15
37
< MagnifyingGlassIcon className = "absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500 peer-focus:text-gray-900" />
16
38
</ div >
You can’t perform that action at this time.
0 commit comments