File tree 2 files changed +32
-5
lines changed
2 files changed +32
-5
lines changed Original file line number Diff line number Diff line change 1
1
import * as React from 'react' ;
2
2
import { useEffect , useRef } from 'react' ;
3
- import { useSearchBox } from 'react-instantsearch' ;
3
+ import { useSearchBox , type UseSearchBoxProps } from 'react-instantsearch' ;
4
+ import useDebounce from '../../hooks/useDebounce' ;
4
5
5
- export default function SearchBox ( ) : JSX . Element {
6
+ export default function SearchBox ( props : UseSearchBoxProps ) : JSX . Element {
6
7
// https://stackoverflow.com/questions/53314857/how-to-focus-something-on-next-render-with-react-hooks
7
- const { query, refine : setQuery } = useSearchBox ( ) ;
8
+ const { query, refine : setQuery } = useSearchBox ( props ) ;
8
9
const inputRef = useRef < HTMLInputElement > ( null ) ;
10
+ const [ searchTerm , setSearchTerm ] = React . useState ( '' ) ;
11
+ const debouncedSearchTerm = useDebounce ( searchTerm , 200 ) ;
12
+ useEffect ( ( ) => {
13
+ if ( debouncedSearchTerm ) {
14
+ setQuery ( searchTerm ) ;
15
+ } else {
16
+ setQuery ( '' ) ;
17
+ }
18
+ } , [ debouncedSearchTerm ] ) ;
9
19
useEffect ( ( ) => {
10
20
if ( inputRef . current ) inputRef . current . focus ( ) ;
11
21
} , [ ] ) ;
@@ -30,8 +40,8 @@ export default function SearchBox(): JSX.Element {
30
40
placeholder = "Search"
31
41
type = "search"
32
42
autoComplete = "off"
33
- value = { query }
34
- onChange = { e => setQuery ( e . target . value ) }
43
+ value = { searchTerm }
44
+ onChange = { e => setSearchTerm ( e . target . value ) }
35
45
ref = { inputRef }
36
46
/>
37
47
</ div >
Original file line number Diff line number Diff line change
1
+ import { useEffect , useState } from 'react' ;
2
+
3
+ export default function useDebounce < T > ( value : T , delay : number ) {
4
+ const [ debouncedValue , setDebouncedValue ] = useState ( value ) ;
5
+
6
+ useEffect ( ( ) => {
7
+ const handler = setTimeout ( ( ) => {
8
+ setDebouncedValue ( value ) ;
9
+ } , delay ) ;
10
+
11
+ return ( ) => {
12
+ clearTimeout ( handler ) ;
13
+ } ;
14
+ } , [ value ] ) ;
15
+
16
+ return debouncedValue ;
17
+ }
You can’t perform that action at this time.
0 commit comments