Looking for pattern for debouncing a useSelect data call from a TextControl component #42281
Replies: 2 comments
-
I figured this out myself -- how you can use the import { debounce } from 'lodash';
import { useSelect } from '@wordpress/data';
import { TextControl } from '@wordpress/components';
// note debounced function defined outside of render function
const debouncedSetValue = debounce( (val,setVal) => {
setVal( val );
}, 500);
export default function edit (props) {
// this value immediately updates for purpose of keeping text input responsive
const [searchTerm, setSearchTerm] = useState("");
// this value only updates after debouncing
const [searchTermDebounceable, setSearchTermDebounceable] = useState("");
// the useSelect hook has the debounced value as it's dependency, so it only makes another call
// when the debounced value changes
var resultsList = useSelect( select => {
var args = {
per_page: 10,
};
if( searchTermDebounceable )
args.search = searchTermDebounceable;
return select('core').getEntityRecords('postType', 'page', args);
}, [ searchTermDebounceable ]);
// called by the textInput, here we immediately update the first value, and update debouncedly the other
const setSearch = (str) => {
setSearchTerm(str);
debouncedSetValue( str, setSearchTermDebounceable);
};
// the text control doesn't use the state function to update, but the intermediary so that both
// state values are updated
<TextControl
value={ searchTerm }
onChange={ setSearch }
label="Search"
/>
...
} |
Beta Was this translation helpful? Give feedback.
-
Since this question / answer was published, there is now For instance, the Media Library uses this method: const [ search, setSearch, debouncedSearch ] = useDebouncedInput(); This gives you the |
Beta Was this translation helpful? Give feedback.
-
I have a useSelect hook that gets some posts (of a custom post type).
I have a
TextControl
element in which the author can type search terms, which will then re-fetch the posts with that search criteria.I would like to debounce that call. I cannot figure out how to do this, other than by using
apiFetch
instead and losing the caching. This is something I'd like to do fairly often so I'm looking for a good pattern to use in these cases. If I debounce thesetSearchTerm
function, theTextControl
input itself doesn't update as user types.Simplified Code:
Beta Was this translation helpful? Give feedback.
All reactions