Skip to content

Commit efc54aa

Browse files
Update problems.tsx with debouncing (#4243)
* Update problems.tsx with debouncing * Added types * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Debouncing works! * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Remove rimraf * Restore old yarn.lock * Removed queryHook from SearchBox.tsx * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 73367e1 commit efc54aa

File tree

2 files changed

+32
-5
lines changed

2 files changed

+32
-5
lines changed

src/components/ProblemsPage/SearchBox.tsx

+15-5
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,21 @@
11
import * as React from 'react';
22
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';
45

5-
export default function SearchBox(): JSX.Element {
6+
export default function SearchBox(props: UseSearchBoxProps): JSX.Element {
67
// 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);
89
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]);
919
useEffect(() => {
1020
if (inputRef.current) inputRef.current.focus();
1121
}, []);
@@ -30,8 +40,8 @@ export default function SearchBox(): JSX.Element {
3040
placeholder="Search"
3141
type="search"
3242
autoComplete="off"
33-
value={query}
34-
onChange={e => setQuery(e.target.value)}
43+
value={searchTerm}
44+
onChange={e => setSearchTerm(e.target.value)}
3545
ref={inputRef}
3646
/>
3747
</div>

src/hooks/useDebounce.tsx

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
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+
}

0 commit comments

Comments
 (0)