11"use client" ;
22
3- import { useState } from "react" ;
3+ import { useState , useCallback } from "react" ;
44import axios from "axios" ;
55import { Search } from "lucide-react" ;
66import Cryptr from "cryptr" ;
7+ import debounce from 'debounce' ;
78import { useRouter } from "next/navigation" ;
89
910const cryptr = new Cryptr (
@@ -16,29 +17,39 @@ const SearchBar = () => {
1617 const [ suggestions , setSuggestions ] = useState < string [ ] > ( [ ] ) ;
1718 const [ error , setError ] = useState < string | null > ( null ) ;
1819
19- const handleSearchChange = async ( e : React . ChangeEvent < HTMLInputElement > ) => {
20- const text = e . target . value ;
21- setSearchText ( text ) ;
2220
23- if ( text . length > 1 ) {
24- try {
25- const searchResponse = await axios . get ( "/api/search" , {
26- params : { text } ,
27- } ) ;
28-
29- const { res : encryptedSearchResponse } = searchResponse . data ;
30- const decryptedSearchResponse = cryptr . decrypt ( encryptedSearchResponse ) ;
31- // console.log("Decrypted Search Response:", decryptedSearchResponse);
32-
33- const { subjects } = JSON . parse ( decryptedSearchResponse ) ;
34- const suggestionList = subjects . map ( ( subjectObj : { subject : string } ) => subjectObj . subject ) ;
35- setSuggestions ( suggestionList ) ;
36- } catch ( error ) {
37- setError ( "Error fetching suggestions" ) ;
21+
22+ const debouncedSearch = useCallback (
23+ debounce ( async ( text : string ) => {
24+ if ( text . length > 1 ) {
25+
26+ try {
27+ const searchResponse = await axios . get ( "http://localhost:3000/api/search" , {
28+ params : { text } ,
29+ } ) ;
30+
31+ const { res : encryptedSearchResponse } = searchResponse . data ;
32+ const decryptedSearchResponse = cryptr . decrypt ( encryptedSearchResponse ) ;
33+ // console.log("Decrypted Search Response:", decryptedSearchResponse);
34+
35+ const { subjects } = JSON . parse ( decryptedSearchResponse ) ;
36+ const suggestionList = subjects . map ( ( subjectObj : { subject : string } ) => subjectObj . subject ) ;
37+ setSuggestions ( suggestionList ) ;
38+ } catch ( error ) {
39+ setError ( "Error fetching suggestions" ) ;
40+
41+ }
42+ } else {
43+ setSuggestions ( [ ] ) ;
3844 }
39- } else {
40- setSuggestions ( [ ] ) ;
41- }
45+ } , 1000 ) ,
46+ [ ]
47+ ) ;
48+
49+ const handleSearchChange = ( e : React . ChangeEvent < HTMLInputElement > ) => {
50+ const text = e . target . value ;
51+ setSearchText ( text ) ;
52+ debouncedSearch ( text ) ;
4253 } ;
4354
4455 const handleSelectSuggestion = async ( suggestion : string ) => {
0 commit comments