@@ -15,12 +15,26 @@ function SearchBarChild({
1515 filtersNotPulled ?: ( ) => void ;
1616} ) {
1717 const router = useRouter ( ) ;
18- const [ count , setCount ] = useState ( 0 ) ;
1918 const [ searchText , setSearchText ] = useState ( "" ) ;
2019 const [ suggestions , setSuggestions ] = useState < string [ ] > ( [ ] ) ;
20+ const [ subjectCounts , setSubjectCounts ] = useState < Record < string , number > > ( { } ) ;
2121 const suggestionsRef = useRef < HTMLUListElement | null > ( null ) ;
2222 const fuzzy = new Fuse ( initialSubjects ) ;
2323
24+ const fetchPaperCount = async ( subjectName : string ) => {
25+ try {
26+ const cleanSubject = subjectName . replace ( / ^ " | " $ / g, "" ) ;
27+ const encodedSubject = encodeURIComponent ( cleanSubject ) ;
28+
29+ const response = await axios . get ( `/api/papers/count?subject=${ encodedSubject } ` ) ;
30+
31+ return response . data . count ?? 0 ;
32+ } catch ( error ) {
33+ console . error ( "Error fetching count for" , subjectName , error ) ;
34+ return 0 ;
35+ }
36+ } ;
37+
2438 const handleSearchChange = async ( e : React . ChangeEvent < HTMLInputElement > ) => {
2539 const text = e . target . value ;
2640 setSearchText ( text ) ;
@@ -35,8 +49,24 @@ function SearchBarChild({
3549 . slice ( 0 , 10 ) ;
3650
3751 setSuggestions ( filteredSuggestions ) ;
52+
53+ // Fetch counts in parallel for each suggestion
54+ const counts = await Promise . all (
55+ filteredSuggestions . map ( async ( subject ) => {
56+ const count = await fetchPaperCount ( subject ) ;
57+ return { subject, count } ;
58+ } )
59+ ) ;
60+
61+ const countsMap = counts . reduce ( ( acc , { subject, count } ) => {
62+ acc [ subject ] = count ;
63+ return acc ;
64+ } , { } as Record < string , number > ) ;
65+
66+ setSubjectCounts ( countsMap ) ;
3867 } else {
3968 setSuggestions ( [ ] ) ;
69+ setSubjectCounts ( { } ) ;
4070 }
4171 } ;
4272
@@ -98,9 +128,10 @@ function SearchBarChild({
98128 < li
99129 key = { index }
100130 onClick = { ( ) => handleSelectSuggestion ( suggestion ) }
101- className = "cursor-pointer truncate p-2 hover:bg-gray-100 dark:hover:bg-gray-800"
131+ className = "flex items-center rounded cursor-pointer truncate p-2 hover:bg-gray-100 dark:hover:bg-gray-800"
102132 >
103- { suggestion }
133+ < div id = "paper_count" className = "bg-[#171720] w-10 h-10 flex items-center justify-center rounded-md text-white text-sm font-semibold mr-4" > { subjectCounts [ suggestion ] ?? "0" } </ div >
134+ < span id = "subject" className = "text-white items-center text-sm sm:text-base tracking-wide" > { suggestion } </ span >
104135 </ li >
105136 ) ) }
106137 </ ul >
0 commit comments