Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
134
rated 0 times [  139] [ 5]  / answers: 1 / hits: 20353  / 7 Years ago, fri, december 1, 2017, 12:00:00

I have a search input, to make API calls on the fly. I'd like to implement debounce to reduce the amount of server calls.



  _debouncedSearch() {
debounce(this.props.fetchRoutes(this.state.searchText), 1000);
}

_updateResults(searchText) {
this.setState({searchText});
this._debouncedSearch();
}


I am expecting debouncedSearch every 1 second. But it is still called on the fly. And throw errors:




Uncaught TypeError: Expected a function
at debounce (lodash.js?3387:10334)



Uncaught Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development.




I feel like this question must get asked around a lot, but none of the solution seems to work for me. Could someone explain to me what exactly is the problem here? I thought debounce is just a setTimeOut.



Thanks


More From » reactjs

 Answers
14

_.debounce is already a carried out function (function returns function ) . Then _debouncedSearch should be an attribute of the class , and not method :



  _debouncedSearch=  debounce(() => this.props.fetchRoutes(this.state.searchText), 1000);


instead of :



  _debouncedSearch() {
debounce(this.props.fetchRoutes(this.state.searchText), 1000);
}


Also, notice , the first argument of _.debounce is a function (() => this.props.fetchRoutes...) , not directly this.props.fetchRoutes...


[#55789] Tuesday, November 28, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nestorjarettg

Total Points: 451
Total Questions: 108
Total Answers: 108

Location: Rwanda
Member since Thu, Feb 10, 2022
2 Years ago
;