1
1
import { outlinedInputClasses } from '@mui/material/OutlinedInput' ;
2
2
import { Theme , ThemeProvider , createTheme , useTheme } from '@mui/material/styles' ;
3
- import React from 'react' ;
3
+ import debounce from 'lodash/debounce' ;
4
+ import React , { useCallback } from 'react' ;
4
5
import { ClickAwayListener } from '../base/ClickAwayListener' ;
5
6
import { TextField } from '../base/TextField' ;
6
7
import { CloseIcon , SearchIcon } from '../icons' ;
@@ -75,11 +76,22 @@ function SearchBar({
75
76
const searchRef = React . useRef < HTMLInputElement | null > ( null ) ;
76
77
const theme = useTheme ( ) ;
77
78
79
+ // Debounce the onSearch function
80
+ const debouncedOnSearch = useCallback (
81
+ debounce ( ( value ) => {
82
+ onSearch ( value ) ;
83
+ } , 300 ) ,
84
+ [ onSearch ]
85
+ ) ;
86
+
78
87
const handleSearchChange = ( event : React . ChangeEvent < HTMLInputElement > ) : void => {
79
- setSearchText ( event . target . value ) ;
88
+ const value = event . target . value ;
89
+ setSearchText ( value ) ;
90
+ debouncedOnSearch ( value ) ;
80
91
} ;
81
92
82
93
const handleClearIconClick = ( ) : void => {
94
+ debouncedOnSearch ( '' ) ;
83
95
setSearchText ( '' ) ;
84
96
setExpanded ( false ) ;
85
97
if ( onClear ) {
@@ -89,6 +101,7 @@ function SearchBar({
89
101
90
102
const handleSearchIconClick = ( ) : void => {
91
103
if ( expanded ) {
104
+ debouncedOnSearch ( '' ) ;
92
105
setSearchText ( '' ) ;
93
106
setExpanded ( false ) ;
94
107
} else {
@@ -101,12 +114,6 @@ function SearchBar({
101
114
}
102
115
} ;
103
116
104
- // const handleClickAway = (): void => {
105
- // if (expanded) {
106
- // setExpanded(false);
107
- // }
108
- // };
109
-
110
117
return (
111
118
< ClickAwayListener
112
119
onClickAway = { ( event ) => {
@@ -125,10 +132,7 @@ function SearchBar({
125
132
< TextField
126
133
variant = "standard"
127
134
value = { searchText }
128
- onChange = { ( e : React . ChangeEvent < HTMLInputElement > ) => {
129
- handleSearchChange ( e ) ;
130
- onSearch ( e . target . value ) ;
131
- } }
135
+ onChange = { handleSearchChange } // Updated to use the new handler
132
136
inputRef = { searchRef }
133
137
placeholder = { placeholder }
134
138
style = { {
0 commit comments