Skip to content

Commit b6d7601

Browse files
committed
refactor: new DebouncedInput component
1 parent 91963b9 commit b6d7601

File tree

2 files changed

+41
-29
lines changed

2 files changed

+41
-29
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import React from 'react';
2+
3+
import type {TextInputProps} from '@gravity-ui/uikit';
4+
import {TextInput} from '@gravity-ui/uikit';
5+
6+
interface SearchProps extends TextInputProps {
7+
debounce?: number;
8+
}
9+
10+
export const DebouncedInput = ({onUpdate, value = '', debounce = 200, ...rest}: SearchProps) => {
11+
const [currentValue, setCurrentValue] = React.useState<string>(value);
12+
13+
const timer = React.useRef<number>();
14+
15+
React.useEffect(() => {
16+
setCurrentValue((prevValue) => {
17+
if (prevValue !== value) {
18+
return value;
19+
}
20+
21+
return prevValue;
22+
});
23+
}, [value]);
24+
25+
const onSearchValueChange = (newValue: string) => {
26+
setCurrentValue(newValue);
27+
28+
window.clearTimeout(timer.current);
29+
timer.current = window.setTimeout(() => {
30+
onUpdate?.(newValue);
31+
}, debounce);
32+
};
33+
34+
return <TextInput value={currentValue} onUpdate={onSearchValueChange} {...rest} />;
35+
};

src/components/Search/Search.tsx

Lines changed: 6 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
import React from 'react';
22

3-
import {TextInput} from '@gravity-ui/uikit';
4-
53
import {cn} from '../../utils/cn';
4+
import {DebouncedInput} from '../DebouncedInput/DebouncedInput';
65

76
import './Search.scss';
87

@@ -22,41 +21,19 @@ export const Search = ({
2221
value = '',
2322
width,
2423
className,
25-
debounce = 200,
24+
debounce,
2625
placeholder,
2726
}: SearchProps) => {
28-
const [searchValue, setSearchValue] = React.useState<string>(value);
29-
30-
const timer = React.useRef<number>();
31-
32-
React.useEffect(() => {
33-
setSearchValue((prevValue) => {
34-
if (prevValue !== value) {
35-
return value;
36-
}
37-
38-
return prevValue;
39-
});
40-
}, [value]);
41-
42-
const onSearchValueChange = (newValue: string) => {
43-
setSearchValue(newValue);
44-
45-
window.clearTimeout(timer.current);
46-
timer.current = window.setTimeout(() => {
47-
onChange?.(newValue);
48-
}, debounce);
49-
};
50-
5127
return (
52-
<TextInput
28+
<DebouncedInput
29+
debounce={debounce}
5330
hasClear
5431
autoFocus
5532
style={{width}}
5633
className={b(null, className)}
5734
placeholder={placeholder}
58-
value={searchValue}
59-
onUpdate={onSearchValueChange}
35+
value={value}
36+
onUpdate={onChange}
6037
/>
6138
);
6239
};

0 commit comments

Comments
 (0)