11"use client" ;
22
33import { SearchIcon } from "lucide-react" ;
4- import React , { useEffect } from "react" ;
4+ import React , { useEffect , useRef } from "react" ;
5+ import { useRouter , useSearchParams } from "next/navigation" ;
56import {
67 SearchBox ,
78 useInstantSearch ,
@@ -10,23 +11,48 @@ import {
1011} from "react-instantsearch" ;
1112
1213export function SearchSection ( ) {
13- const { results } = useInstantSearch ( { } ) ;
14- const { query } = useSearchBox ( ) ;
14+ const { results } = useInstantSearch ( ) ;
15+ const { query, refine } = useSearchBox ( ) ;
16+ const isInitialMount = useRef ( true ) ;
17+ const router = useRouter ( ) ;
18+ const searchParams = useSearchParams ( ) ;
1519
1620 useEffect ( ( ) => {
17- console . log ( results ) ;
18- } , [ results ] ) ;
21+ if ( isInitialMount . current ) {
22+ const initialQuery = searchParams . get ( "query" ) || "" ;
23+ if ( initialQuery !== query ) {
24+ refine ( initialQuery ) ;
25+ }
26+ isInitialMount . current = false ;
27+ }
28+ } , [ refine , searchParams ] ) ;
29+
30+ useEffect ( ( ) => {
31+ if ( isInitialMount . current ) return ;
32+
33+ const currentQuery = searchParams . get ( "query" ) || "" ;
34+
35+ if ( currentQuery !== query ) {
36+ const params = new URLSearchParams ( searchParams ) ;
37+ if ( query ) {
38+ params . set ( "query" , query ) ;
39+ } else {
40+ params . delete ( "query" ) ;
41+ }
42+ router . push ( `?${ params . toString ( ) } ` , { scroll : false } ) ;
43+ }
44+ } , [ query , router , searchParams ] ) ;
1945
2046 return (
21- < div id = "search" className = "mb-8 max-w-3xl mx-auto" >
47+ < div className = "max-w-3xl mx-auto" >
2248 < div className = "border-2 border-gray-200 rounded-xl transition-all duration-200 shadow-sm hover:shadow-md" >
2349 < div className = "flex items-center" >
2450 < div className = "relative flex-1" >
2551 < div className = "absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none z-10" >
2652 < SearchIcon className = "h-5 w-5 text-gray-400" />
2753 </ div >
2854 < SearchBox
29- placeholder = { `Search through APIs...` }
55+ placeholder = { `Search through ${ results . nbHits . toLocaleString ( ) } APIs...` }
3056 classNames = { {
3157 form : "relative" ,
3258 input :
@@ -48,11 +74,18 @@ export function SearchSection() {
4874 </ div >
4975 </ div >
5076 </ div >
51- { query && (
52- < div className = "mt-3 text-lg text-gray-600 text-center" >
77+ < div
78+ className = "my-3 min-h-[1.75rem] text-lg text-gray-600 text-center"
79+ aria-live = "polite"
80+ >
81+ < span
82+ className = { `inline-block transition-opacity duration-200 ${
83+ query ? "opacity-100" : "opacity-0"
84+ } `}
85+ >
5386 { results . nbHits . toLocaleString ( ) } APIs found
54- </ div >
55- ) }
87+ </ span >
88+ </ div >
5689 </ div >
5790 ) ;
5891}
0 commit comments