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