#StackBounty: #reactjs #lodash #onchange #debounce Why is my React debounce handler never called?

Bounty: 100

I’m using React 16.13.0 and lodash. I was recommended to use debounce as a way to properly send search requests to my server as a user types in their search term. I implemented this …

...

const handleChange = (event, searchTerm, setSearchTerm, setSearchResults) => {
  console.log("search term:" + searchTerm);
  const query = event.target.value;
  setSearchTerm(query);
  if (!query) {
    setSearchResults( [] );
  } else {
    doSearch(query, searchTerm, setSearchResults);
  }
}

const getDebouncedHandler = (e, handler, delay) => {
  console.log("value:" + e.target.value);
  _.debounce(handler, delay);
}
...

const Search = (props) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [searchResults, setSearchResults] = useState([]);

  const renderSearchResults = ...

  return (
    <div className="searchForm">
      <input
        type="text"
        placeholder="Search"
        value={searchTerm}
        onChange={(e) => {getDebouncedHandler(e, (e) => {handleChange(e, searchTerm, setSearchTerm, setSearchResults); }, 100)}}
      />
      {renderSearchResults()}
    </div>
  );
}

export default Search;

The problem is, although I see my "getDebouncedHandler" method getting called, I don’t think

_.debounce(handler, delay);

is doing anything because I never see the method listed there invoked. What else do I need to do to get debounce handler invoked properly?

Edit: Adding in the logic I’m using for "doSearch"

const doSearch = (query, searchTerm, setSearchResults) => {
  console.log("before fetch, with query:" + query);
  const searchUrl = "/coops/?contains=" + encodeURIComponent(query);
  fetch(searchUrl, {
    method: "GET",
  })
    .then((response) => response.json())
    .then((data) => {
      console.log("returning data for " + searchTerm + " query:" + query);
      console.log(data);
      if (query === searchTerm) {
        console.log("setting search results for search term:" + searchTerm);
        setSearchResults(data);
      }
    });
}


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.