1
1
"use client" ;
2
2
3
- import { useState } from "react" ;
3
+ import { useState , useCallback } from "react" ;
4
4
import axios from "axios" ;
5
5
import { Search } from "lucide-react" ;
6
6
import Cryptr from "cryptr" ;
7
+ import debounce from 'debounce' ;
7
8
import { useRouter } from "next/navigation" ;
8
9
9
10
const cryptr = new Cryptr (
@@ -16,29 +17,39 @@ const SearchBar = () => {
16
17
const [ suggestions , setSuggestions ] = useState < string [ ] > ( [ ] ) ;
17
18
const [ error , setError ] = useState < string | null > ( null ) ;
18
19
19
- const handleSearchChange = async ( e : React . ChangeEvent < HTMLInputElement > ) => {
20
- const text = e . target . value ;
21
- setSearchText ( text ) ;
22
20
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 ( [ ] ) ;
38
44
}
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 ) ;
42
53
} ;
43
54
44
55
const handleSelectSuggestion = async ( suggestion : string ) => {
0 commit comments