Skip to content

Instantly share code, notes, and snippets.

@anthowen
Last active November 29, 2022 09:33
Show Gist options
  • Save anthowen/0fae7da675de3371be2fb1bf26a0a945 to your computer and use it in GitHub Desktop.
Save anthowen/0fae7da675de3371be2fb1bf26a0a945 to your computer and use it in GitHub Desktop.
This shows how to implement debounced search (interacting with API) in a custom input element
// Note: I write down only essential parts of the component, because the other part can make sense without itself.
import { useFilter } from 'hooks/useFilter.ts';
import debounce from 'lib/debounce';
function InputSearch({...} : InputSearchInterface) {
// api - a search api wrapper that returns promise
// useFilter - a custom react hook used for search (https://gist.github.com/anthowen/7309f9d54dcdeefcefab1e37a75d716c)
const [{ results, isSearching }, doFilter] = useFilter<T>(api, null, []);
const debounceLimit = 800; // 800ms
const debouncedSearch = useMemo(
() => debounce((value) => doFilter(value), debounceLimit),
[doFilter],
);
const handleInputChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
e.persist(); // https://fb.me/react-event-pooling
debouncedSearch(e.target.value);
},
[debouncedSearch],
);
return (
// ...
<input
type="text"
name="searchFilter"
onChange={handleInputChange}
/>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment