slorber / awesome-debounce-promise

Debounce your API calls easily and stay in promised land.
https://sebastienlorber.com
391 stars 9 forks source link

ReadMe Suggestion: don't declare async search function inside the handle change function #7

Closed stefems closed 5 years ago

stefems commented 5 years ago

Smarter users than me probably didn't have this issue but if you declare your search and debouncer functions inside the handler, like in the code below, the debouncer will still fire the async request for every text change. (I think the reason is because the declaration of the functions in that scope means that the references are different on each change, meaning that the async requests aren't cancelled and are still called? Your wording might be better...) Perhaps not a necessary suggestion but it might help people in the future. Thanks.

class SearchInputAndResults extends React.Component {
  state = {
    text: '',
    results: null,
  };

  handleTextChange = async text => {
    const searchAPI = text => fetch('/search?text=' + encodeURIComponent(text));
    const searchAPIDebounced = AwesomeDebouncePromise(searchAPI, 500);
    this.setState({ text, results: null });
    const result = await searchAPIDebounced(text);
    this.setState({ result });
  };

  componentWillUnmount() {
    this.setState = () => {};
  }
}
slorber commented 5 years ago

hi

I've added a "troubleshooting" section. Your error is the most common users usually make with debouncing, because the function is "stateful" (whether it's with callback or promises). I've wrote an answer on SO about this: https://stackoverflow.com/a/28046731/82609

https://github.com/slorber/awesome-debounce-promise/blob/master/README.md#my-debouncing-function-always-fire-and-is-not-debounced