-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathDebounceField.component.js
65 lines (56 loc) · 1.64 KB
/
DebounceField.component.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// @flow
import * as React from 'react';
import { debounce } from 'lodash';
import { TextInput } from '../internal/TextInput/TextInput.component';
type Props = {
onDebounced: (event: SyntheticEvent<HTMLInputElement>) => void,
value: ?string,
};
type State = {
value: string,
};
/**
* Text field exposing a callback method triggered when the input is debounced
* @class DebounceField
*/
export class DebounceField extends React.Component<Props, State> {
debouncer: Function;
constructor(props: Props) {
super(props);
this.state = {
value: this.props.value || '',
};
this.debouncer = debounce(this.handleDebounced, 500);
}
UNSAFE_componentWillReceiveProps(nextProps: Props) {
if (nextProps.value !== this.props.value) {
this.setState({
value: nextProps.value || '',
});
}
}
componentWillUnmount() {
this.debouncer.cancel();
}
handleDebounced = (event: SyntheticEvent<HTMLInputElement>) => {
this.props.onDebounced(event);
}
handleChange = (event: SyntheticEvent<HTMLInputElement>) => {
this.setState({
value: event.currentTarget.value,
});
this.debouncer({ ...event });
}
render() {
const { onDebounced, value, ...passOnProps } = this.props;
const { value: stateValue } = this.state;
return (
// $FlowFixMe[cannot-spread-inexact] automated comment
<TextInput
onChange={this.handleChange}
value={stateValue}
{...passOnProps}
/>
);
}
}