EDIT: solved
I have a simple react page which has a search box where each key press updates a state variable with the current value and children objects decide their visibility based on that string. I'd like to debounce this so it's not updated on every letter but when the user hasn't hit the key in a half a second or whatever. I found lots of recommendations for lodash, but all of the docs seem to assume a lot - like you're creating a npm app instead of running in a browser and I've been unable to make it work.
So the code as it stands today without debouncing is:
class PickForm extends React.Component {
constructor(props) {
super(props);
this.handleSearchChange = this.handleSearchChange.bind(this);
...
this.state = {
...
search: '',
};
}
handleSearchChange(e) {
this.setState({search: e.target.value.toLowerCase()})
}
...
}
Then various children render components with:
style={{visibility: this.visibility(this.props.search)}}
where the constructor for this children does:
this.visibility = this.visibility.bind(this);
Of all the articles I found, https://medium.com/@anuhosad/debouncing-events-with-react-b8c405c33273 seems to be exactly what I wanted, so I changed handleSearchChange to be:
handleSearchChange(e) {
e.persist();
if (!this.debouncedFn) {
this.debouncedFn = _.debounce(() => {
this.setState({search: e.target.value.toLowerCase()});
}, 300);
}
this.debouncedFn();
}
which leaves my text box read-only. :(
Thanks,
- Phil
Top comments (1)
aaand changing
value
fordefaultValue
fixed it!