Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using debounce for search input in react

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

like image 855
leogoesger Avatar asked Dec 01 '17 18:12

leogoesger


3 Answers

Recently found this issue helpful. Here's my optimized solution:

const [searchTerm, setSearchTerm] = useState("");
const [result, setResult] = useState([]);

async function fetchData(searchTerm: string) {
  const { data } = await client.query(searchTerm);
  setResult(data);
}

const debounceLoadData = useMemo(() => debounce(fetchData, 700), []);

useEffect(() => {
  window.addEventListener("keydown", debounceLoadData(searchTerm));
  return () => {
    window.removeEventListener("keydown", debounceLoadData(searchTerm));
  };
}, [searchTerm]);

This will only call the fetchData() function once after the user stops typing for 700ms. Then I use useMemo to cache every result. If the user searches the same value multiple times it will return the cached value and not invoke the fetchData() function more than necessary.

like image 181
Ryan Avatar answered Nov 11 '22 10:11

Ryan


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!

like image 42
leogoesger Avatar answered Nov 11 '22 08:11

leogoesger


_.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...

like image 31
Abdennour TOUMI Avatar answered Nov 11 '22 10:11

Abdennour TOUMI