1
- import React from 'react' ;
1
+ import React , { useCallback } from 'react' ;
2
+ import type { ChangeEvent } from 'react' ;
2
3
import { useSelector } from 'react-redux' ;
3
- import type { AppState } from '../../../../types' ;
4
- import { actions } from '../../../../state' ;
4
+
5
5
import { UISearchBox } from '@sap-ux/ui-components' ;
6
6
7
+ import type { AppState } from '../../../../types' ;
8
+ import { actions } from '../../../../state' ;
7
9
import { Filters } from '../Filters' ;
8
10
9
- let timer : NodeJS . Timeout ;
11
+ const SEARCH_TIMEOUT = 250 ;
12
+
10
13
/**
11
14
*
12
15
* @returns An input field
13
16
*/
14
17
export function SearchField ( ) {
15
18
const appState = useSelector < AppState , AppState > ( ( state ) => state ) ;
16
19
17
- const onChange = ( value : string ) : void => {
18
- clearTimeout ( timer ) ;
19
- actions . setQueryValue ( value ) ;
20
- timer = setTimeout ( ( ) => {
21
- actions . searchTree ( {
22
- query : value ,
23
- filters : {
24
- product : appState . selectedProductFilters ,
25
- component : appState . selectedComponentFilters
26
- } ,
27
- paging : {
28
- responseSize : appState . pageSize ,
29
- offset : 0
30
- }
31
- } ) ;
32
- } , 100 ) ;
20
+ const debounce = ( fn : Function , delay = SEARCH_TIMEOUT ) => {
21
+ let timeoutId : ReturnType < typeof setTimeout > ;
22
+ return function ( this : any , ...args : any [ ] ) {
23
+ clearTimeout ( timeoutId ) ;
24
+ timeoutId = setTimeout ( ( ) => fn . apply ( this , args ) , delay ) ;
25
+ } ;
26
+ } ;
27
+
28
+ const debounceSearch = useCallback (
29
+ debounce (
30
+ ( newSearchTerm : string ) =>
31
+ actions . searchTree ( {
32
+ query : newSearchTerm ,
33
+ filters : {
34
+ product : appState . selectedProductFilters ,
35
+ component : appState . selectedComponentFilters
36
+ } ,
37
+ paging : {
38
+ responseSize : appState . pageSize ,
39
+ offset : 0
40
+ }
41
+ } ) ,
42
+ SEARCH_TIMEOUT
43
+ ) ,
44
+ [ ]
45
+ ) ;
46
+
47
+ const onClearSearchTerm = ( ) : void => {
48
+ actions . setQueryValue ( '' ) ;
49
+ debounceSearch ( '' ) ;
50
+ } ;
51
+
52
+ const onChangeSearchTerm = ( _ ?: ChangeEvent < HTMLInputElement > | undefined , newSearchTerm = '' ) : void => {
53
+ actions . setQueryValue ( newSearchTerm ) ;
54
+ debounceSearch ( newSearchTerm ) ;
33
55
} ;
34
56
35
57
return (
@@ -40,8 +62,8 @@ export function SearchField() {
40
62
readOnly = { appState . networkStatus === 'LOADING' }
41
63
placeholder = "Search Guided Answers"
42
64
id = "search-field"
43
- onClear = { ( ) => onChange ( '' ) }
44
- onChange = { ( e : any ) => onChange ( e ?. target ?. value || '' ) } > </ UISearchBox >
65
+ onClear = { onClearSearchTerm }
66
+ onChange = { onChangeSearchTerm } > </ UISearchBox >
45
67
{ appState . activeScreen === 'SEARCH' && < Filters /> }
46
68
</ div >
47
69
) ;
0 commit comments