Here's my use case, a simple React component with a text input which filters the elements of a list:
const myArray = [...];
// Inside React component:
handleChange = ({target: {value}}) => this.setState({value});
render() {
return (
<div>
<input onChange={this.handleChange} value={this.state.value} />
<ul>
{myArray.filter(v => v.includes(this.state.value)).map(v => <li>{v}</li>)}
</ul>
</div>
);
}
With this code, everytime I change the text inside the input, the elements inside the list changes immediately.
What I want to achieve: the user types in the filter text, that text updates immediately in the text input (normal), but I wish the elements inside the list not to update immediately, but let's say 500ms after the user finished typing.
So basically:
<input>
, list elements don'tEdit:
What I tried:
import throttle from 'lodash/throttle';
const myArray = [...];
// Inside React component:
handleChange = ({target: {value}}) => this.setState({value});
calculateMatches = throttle(() => {
const matches = myArray.filter(v => v.includes(this.state.value))
return matches;
}, 500);
render() {
return (
<div>
<input onChange={this.handleChange} value={this.state.value} />
<ul>
{this.calculateMatches().map(v => <li>{v}</li>)}
</ul>
</div>
);
}
But this throttles every 500ms, so if the user continues typing for 1600ms, it will re-update the list 3 times.
©2020 All rights reserved.