File tree Expand file tree Collapse file tree 2 files changed +68
-0
lines changed
hooks/use-debounced-input Expand file tree Collapse file tree 2 files changed +68
-0
lines changed Original file line number Diff line number Diff line change 1+ import { useEffect , useState } from '@wordpress/element' ;
2+ import { useDebounce } from '@wordpress/compose' ;
3+
4+ type DebouncedInputOptions = {
5+ delay : number ;
6+ } ;
7+
8+ /**
9+ * Helper hook for input fields that need to debounce the value before using it.
10+ *
11+ * @param {string } defaultValue The default value to use.
12+ * @param {DebouncedInputOptions } options Set of options for useDebounce, 350ms is the default
13+ *
14+ * @returns The input value, the setter and the debounced input value.
15+ */
16+ export function useDebouncedInput (
17+ defaultValue : string = '' ,
18+ options : DebouncedInputOptions = { delay : 500 } ,
19+ ) : [ string , ( value : string ) => void , string ] {
20+ const [ input , setInput ] = useState < string > ( defaultValue ) ;
21+ const [ debouncedInput , setDebouncedState ] = useState ( defaultValue ) ;
22+ const { delay } = options ;
23+ const setDebouncedInput = useDebounce ( setDebouncedState , delay ) ;
24+
25+ useEffect ( ( ) => {
26+ setDebouncedInput ( input ) ;
27+ } , [ input , setDebouncedInput ] ) ;
28+
29+ return [ input , setInput , debouncedInput ] ;
30+ }
Original file line number Diff line number Diff line change 1+ # ` useDebouncedInput `
2+
3+ The ` useDebouncedInput ` hook is a revision of the ` @wordpress/components ` version of the hook which exposes options, specifically to configure the debounce delay.
4+
5+ ## Usage
6+
7+ ``` js
8+ import { SearchControl } from ' @wordpress/components' ;
9+ import { useDebouncedInput } from ' @10up/block-components' ;
10+
11+ function BlockEdit (props ) {
12+ const [searchInput , setSearchString , searchString ] = useDebouncedInput (' ' );
13+ ...
14+ async fetchTitles => {
15+ let options = await apiFetch ({
16+ path: addQueryArgs (' /wp/v2/search' , {
17+ search: searchString,
18+ ...
19+ })
20+ });
21+ options = options .filter (option => option .title !== ' ' );
22+
23+ return options;
24+ };
25+ ...
26+ return (
27+ <>
28+ < SearchControl
29+ value= {searchInput}
30+ onChange= {(newSearchString : string ) => {
31+ setSearchString (newSearchString);
32+ }}
33+ / >
34+ ...
35+ < / >
36+ );
37+ }
38+ ```
You can’t perform that action at this time.
0 commit comments