using debounce for search input in react

leogoesger picture leogoesger · Dec 1, 2017 · Viewed 11.9k times · Source

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

Answer

leogoesger picture leogoesger · Dec 1, 2017
constructor(props) {
    super(props);
    this.state = {
      searchText: '',
    };
    this._debouncedSearch = debounce(
      () => this.props.fetchRoutes(this.state.searchText),
      1000
    );
  }

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

Here is the fullworking code in case someone needs it!