Reputation: 883
I'm trying to implement a simple search in a view.
I have a TextInput component where user can type a search term.
The TextInput is handled by a function which waits 2 seconds then sends the text term to an api.
Here is the api the handler fonction:
performSearch(text){
var typingTimer = null;
if(typingTimer){
typingTimer = null;
}
typingTimer = setTimeout( () => {
this.setState({
search: text
});
console.log(this.state.search);
}, 2000);
}
Here is the behavior I would love to have: if user type something the api call is only made 2 seconds after the user hits the last key. If the user hits another key before 2 seconds, only the last value of the TextInput must be sent.
Unfortunately I can achieve it for now. Any help would be highly appreciated. Cheers
Upvotes: 0
Views: 470
Reputation: 2301
try this:
performSearch(text){
clearTimeout(this.typingTimer);// this will cancel the previous timer
this.typingTimer = setTimeout( () => {
this.setState({
search: text
});
}, 2000);
}
Upvotes: 1